gpt4 book ai didi

linux - 在 linux shell 脚本中传递参数和使用命名参数时避免位置引用

转载 作者:太空宇宙 更新时间:2023-11-04 10:06:49 26 4
gpt4 key购买 nike

我有一个脚本“/tmp/SampleScript.sh”,内容如下:

echo "First arg: $1"
echo "Second arg: $2"

如果我按如下方式运行此脚本:

[oracle@xxxxx tmp]$ ./SampleScript.sh FirstParamPassed SecondParamPassed
Output Is:
First arg: FirstParamPassed
Second arg: SecondParamPassed

但如果我将其运行为:

[oracle@xxxxx tmp]$ ./SampleScript.sh SecondParamPassed FirstParamPassed
Output Is:
First arg: SecondParamPassed
Second arg: FirstParamPassed

我想要这样的输出:

echo "First arg: $FirstParamPassed"
echo "Second arg: $FirstParamPassed"
[oracle@xxxxx tmp]$ ./SampleScript.sh SecondParamPassed=2 FirstParamPassed=1
First arg: 1
Second arg: 2

如何在 REHL shell 脚本中使用这种类型的命名变量。我已经完成了这个答案Is there a way to avoid positional arguments in bash?但无法理解如何在我的案例中实现。

最佳答案

改用环境变量。将您的脚本编写为

echo "First arg: $FirstParamPassed"
echo "Second arg: $SecondParamPassed"

然后称它为

FirstParamPassed=1 SecondParamPassed=2 ./SampleScript.sh

SecondParamPassed=2 FirstParamPassed=1 ./SampleScript.sh

预命令分配的顺序无关紧要。

如果您在调用脚本之前启用 -k 选项,您可以将赋值放在脚本之后,模仿您最初的尝试。

$ set -k
$ ./SampleScript.sh SecondParamPassed=2 FirstParamPassed=1
First arg: 1
Second arg: 2

同样,分配的顺序并不重要。


您可以修改脚本以允许通过位置参数设置值。只有在尚未设置环境变量时才会使用位置参数。

: ${FirstParamPassed:=$1}
: ${SecondParamPassed:=$2}
echo "First arg: $FirstParamPassed"
echo "Second arg: $SecondParamPassed"

例如,

$ SecondParamPassed=2 ./SampleScript.sh 6 notused
First arg: 6
Second arg: 2

关于linux - 在 linux shell 脚本中传递参数和使用命名参数时避免位置引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51967513/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com