【发布时间】:2020-01-26 11:58:33
【问题描述】:
我在 bash 脚本中有很多预定义的变量,比如
$adr1="address"
$out1="first output"
$adr2="another address"
$out2="second output"
并且数字取自外部源,例如,如果数字为 1,我希望变量 $adr 的值来自 $adr1,$out 的值来自 $out1。如果数字是 2,$adr 应该是 $adr2 的值,$out 应该是 $out2 等的值。
编辑 27.01.2020: 好的,可能我不够清楚,再举个例子试试:
#! /bin/bash
adr1="address"
out1="first-output"
adr2="another-address"
out2="second-output"
if [ $1 -eq 1 ]; then
adr=$adr1
out=$out1
elif [ $1 -eq 2 ]; then
adr=$adr2
out=$out2
fi
echo "adr=$adr, out=$out"
现在我将运行脚本(假设它被命名为 test.sh):
./test.sh 1
adr=address, out=first-output
再跑一次:
./test.sh 2
adr=another-address, out=second-output
我想去掉这个 if - elif 语句,因为后面还会有 adr3 和 out3 以及 adr4 和 out4 等。
【问题讨论】:
-
这能回答你的问题吗? Dynamic variable names in Bash