我有以下 shell 脚本,假设它的名称为 test.sh
#!/bin/bash
b_x='it is the value of bx'
c_x='it is the value of cx'
case "$1" in
"b")
echo $1_x # it's doesn't work; I want to echo $b_x
;;
"c")
echo $1_x # it's doesn't work; I want to echo $c_x
;;
esac
然后我想调用脚本;
./test.sh b # I want the output is "it is the value of bx"
./test.sh c # I want the output is "it is the value of cx"
最佳答案
你不需要case
。只需使用间接变量名扩展:
b_x='it is the value of bx'
c_x='it is the value of cx'
var="${1}_x"
echo "${!var}"
然后运行它:
$> bash test.sh b
it is the value of bx
$> bash test.sh c
it is the value of cx
关于linux - 如何通过字符串组装变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38371740/