从数字中选择的变量



我在bash脚本中有很多预定义的变量,例如

$adr1="address"
$out1="first output"
$adr2="another address"
$out2="second output"

数字取自外部源,因此例如,如果数字为 1,我希望变量$adr为 $adr 1 的值,$out为 $out 1 的值。如果数字

为 2,则$adr的值应为 $adr 2,$out的值应为 $out 2 等。编辑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

我想消除这个如果 - 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"

最新更新