Linux 从数字中选择变量

Linux 从数字中选择变量,linux,bash,variables,Linux,Bash,Variables,我在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 ad

我在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 2
adr=another-address, out=second-output

我想取消这个if-elif语句,因为以后还会有adr3和out3、adr4和out4等等。

你可以很容易地像键值法那样做,它是完全动态的
制作一个脚本文件并保存它,在这种情况下,我的文件名是
freeman.sh

#! /bin/bash

for i in $@
do
        case $i in 
           ?*=?*) 
              declare "${i%=*}=${i#*=}" ;;
           *) 
              break

        esac
done
# you can echo your variables like this or use $@ to print all
echo $adr1
echo $out1
echo $adr2
echo $out2
为了测试我们的脚本,我们可以这样做:

$ bash freeman.sh adr1="address" out1="first-output" adr2="another-address" out2="second-output"
输出为:

address
first-output
another-address
second-output

我认为您需要的结构如下:

#! /bin/bash

adr1="address"
out1="first-output"
adr2="another-address"
out2="second-output"
# and so on...

eval adr='$adr'$1
eval out='$out'$1

echo "adr=$adr, out=$out"

这回答了你的问题吗?$adr和$out内的空格和新行使用此结构正确处理。其他可能性包括:
eval adr=\$adr$1
eval adr=“\$adr$1”
#! /bin/bash

adr1="address"
out1="first-output"
adr2="another-address"
out2="second-output"
# and so on...

eval adr='$adr'$1
eval out='$out'$1

echo "adr=$adr, out=$out"