2

我在 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 等。

4

2 回答 2

1

你可以很容易地做像键值方法,它是完全动态的!
制作一个脚本文件并保存它,在这种情况下我的文件名是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
于 2020-01-26T12:59:37.303 回答
0

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

#! /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"
于 2020-01-27T20:46:57.517 回答