bash,用另一个变量替换变量的一部分

时间:2012-08-24 16:48:09

标签: bash substitution

#!/bin/bash

SUNDAY_MENU=BREAD
MONDAY_MENU=APPLES

TODAY=MONDAY


ECHO "I want ${${TODAY}_MENU}" # does not work, bad substitution

ECHO "I want ${`echo $TODAY`_MENU}" # does not work, bad substitution

任何想法?

2 个答案:

答案 0 :(得分:6)

像这样使用variable indirection

varname=${TODAY}_MENU
echo ${!varname}

但是,如果您使用的是Bash 4或更高版本,则最好使用associative array

menu=([sunday]=bread [monday]=apples)
echo ${menu[$TODAY]}

答案 1 :(得分:0)

我使用eval函数

#!/bin/bash

SUNDAY_MENU=BREAD
MONDAY_MENU=APPLES

TODAY=MONDAY

eval TODAY_MENU=\$\{${TODAY}_MENU\}

echo "I want ${TODAY_MENU}"