2013-08-29 58 views
0

好的,所以我試圖使用變量值,然後使用該變量的值,以獲取該變量的值。使用變量的值來使用變量值

因此,我的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. 

它會被稱爲:

USAGE: cecho "MESSAGE" color 

所以,基本上腳本點對色彩$message與任何$2等於。

Anyidea如何可以:

獲取變量的值與$2名,

2.更好的寫作這種script的方式?

回答

5

查找間接(的Shell Parameter Expansion第四段):

${!color} 

如果color=white,這將從$white,這是你以後生成的字符串,我想。您也可以查看eval命令,但它通常不如符號(更危險)。

至於更好的辦法來寫劇本:我會推遲echo -e直到我使用的顏色,除非你打算點(.)我不會導出變量或source腳本:

black='\E[30;47m' 
... 
white='\E[37;47m' 

... 
color="$2" 
... 

echo -e "${!color}" 
+0

正是我在找什麼和工作得令人驚訝,感謝您的解決方案和提示! –

相關問題