Bash脚本:如何设置类并对这些类应用颜色。

Bash脚本:如何设置类并对这些类应用颜色。,bash,colors,Bash,Colors,我有一个脚本,当前我正在将颜色格式应用于我希望使用颜色的每一行代码 ## Shell color variables red=`tput setaf 1` green=`tput setaf 2` yellow=`tput setaf 3` reset=`tput sgr0` bold=`tput bold` ## Questions = yellow ## Actions = green ## Errors = red read -p "${yellow}${bol

我有一个脚本,当前我正在将颜色格式应用于我希望使用颜色的每一行代码

 ## Shell color variables

 red=`tput setaf 1`
 green=`tput setaf 2`
 yellow=`tput setaf 3`
 reset=`tput sgr0`
 bold=`tput bold`

 ## Questions = yellow
 ## Actions = green
 ## Errors = red


 read -p "${yellow}${bold}What is your name?${reset} " hostname
 echo "${green}Pulling up a list of files that begin with $FILELIST ...${reset}"
 echo "${red}File already exists! Exiting...${reset}"
这不是一个完整的脚本,只是它看起来像什么样的一个示例,但在大多数情况下,它主要是使用echos将颜色应用到脚本输出以及上面看到的内容。问题是,对于每一行,无论是问题、行动还是错误,我都在每一行定义它。这是一个非常冗长的脚本,逐行应用格式是非常乏味的工作。一定有更好的办法。有没有一种方法可以定义类并将颜色应用于这些类,这样我就不必在每一行上指定它?我在想,因为我的大多数彩色线条都使用echo,所以只需在顶部创建一些echo变量,如下所示:

##This is for a question:

echoq=$(echo -e "\033[1;93m"this is my question text in yellow"\033[m")

or 

echoq=$(${yelllow}${bold}"this is my question text in yellow"${reset})

##This is for an action

echoa=$(echo -e "\033[1;91m"this is my action text in red"\033[m")

or 

echoa=$(${red}${bold}"this is my action text in red"${reset})
一旦我定义了所有的变量,我就使用echoq、echoa或echor,如果它适用的话。这样做可行吗?

当然可以,但是---

然后,您可以将
echoq
复制到
echoa
echor
,只需将
${yellow}
更改为
${red}
或任何您想要的颜色或转义序列即可

编辑:在回答您的问题时,
echoq
中的字符串有三个部分,都卡在一起:

${yellow}            The value of the "yellow" variable --- change to yellow
         $1          The parameter to echoq.  You can also write this as ${1}.
           ${reset}  The value of the "reset" variable --- Reset the terminal

所以
$1$
实际上是
$1
加上
${reset}
的前导
$
。在每个函数中,你仍然使用<代码> 1美元<代码>,因为每个函数都像每个脚本一样得到它自己的参数。我会在所有函数中使用$1$,还是需要在每个函数中增加该数字1?@user53029经过编辑解释。这是一个正确的答案+1.但是我建议使用
“$@”
而不是
“$1”
,因为这样你就可以使用
echo
-类似的语法:
echoq这是一个问题
@anishsane很好的观点;那很好。实际上,我选择了
$1
是为了避免让OP感到意外。想象一下
echop你叫什么名字?
(不
)运行在一个包含名为
name
的文件的目录中。由于路径名扩展,结果将是
What is your names
(我刚刚测试了这个;)。由于OP对“echo”很满意,因此我认为最好还是坚持下去,避免因意外扩展而造成混淆。^^Hmm。。。说得对。此外,我还编写了如下函数:
printf“%s”$yellow;回音“$@”;printf“%s”“$reset”
,以便
echor
的所有选项将按原样传递给
echo
。。。
${yellow}            The value of the "yellow" variable --- change to yellow
         $1          The parameter to echoq.  You can also write this as ${1}.
           ${reset}  The value of the "reset" variable --- Reset the terminal