【问题标题】:variable selected from number从数字中选择的变量
【发布时间】: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 等。

【问题讨论】:

标签: linux bash variables


【解决方案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

【讨论】:

    【解决方案2】:

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

    #! /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$1eval adr="\$adr$1"
    猜你喜欢
    • 2020-04-06
    • 2013-07-26
    • 2016-07-19
    • 1970-01-01
    • 2021-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多