好吧,所以我试图使用变量值然后使用该变量的值来获取该变量的值.
因此,我script将其$1作为一条消息,然后将其$2作为打印出来的颜色.
#!/bin/bash
# TAKES $1 as MSG and $2 as COLOR.
export black='echo -e "\E[30;47m"'
export red='echo -e "\E[31;47m"'
export green='echo -e "\E[32;47m"'
export yellow='echo -e "\E[33;47m"'
export blue='echo -e "\E[34;47m"'
export magenta='echo -e "\E[35;47m"'
export cyan='echo -e "\E[36;47m"'
export white='echo -e "\E[37;47m"'
# VARIABLES
export color="$2" # Set Color
export message="$1" # Set MSG
# Use $color for what variable to substitute with, so we get the echos.
# Previously tried \$$color to get $whatever_$2_was but it wouldn't get the value.
\$$color
echo "$message" # Echo Message.
tput sgr0 # Reset to normal.
Run Code Online (Sandbox Code Playgroud)
它被称为:
USAGE: cecho "MESSAGE" color
Run Code Online (Sandbox Code Playgroud)
因此,基本上脚本指向的是$message用任何$2等于颜色.
Anyidea如何:
1.使用$2名称获取变量的值,
要么
2.更好的写作方式script?
查找间接(Shell参数扩展的第四段):
${!color}
Run Code Online (Sandbox Code Playgroud)
如果color=white,这将生成字符串$white,这是你所追求的,我想.你也可以查找eval命令,但它通常不符合(比${!color}表示法更危险).
至于编写脚本的更好方法:我会推迟echo -e使用颜色,除非你计划使用dot(.)或source脚本,否则我不会导出变量:
black='\E[30;47m'
...
white='\E[37;47m'
...
color="$2"
...
echo -e "${!color}"
Run Code Online (Sandbox Code Playgroud)