Bash 命令行参数,替换变量的默认值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16319720/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bash command line arguments, replacing defaults for variables
提问by Lanrest
I have a script which has several input files, generally these are defaults stored in a standard place and called by the script.
我有一个脚本,它有几个输入文件,通常这些是存储在标准位置并由脚本调用的默认值。
However, sometimes it is necessary to run it with changed inputs.
但是,有时需要使用更改的输入运行它。
In the script I currently have, say, three variables, $A $B, and $C. Now I want to run it with a non default $B, and tomorrow I may want to run it with a non default $A and $B.
在脚本中,我目前有三个变量,$A、$B 和 $C。现在我想用非默认的 $B 运行它,明天我可能想用非默认的 $A 和 $B 运行它。
I have had a look around at how to parse command line arguments:
我查看了如何解析命令行参数:
How do I parse command line arguments in Bash?
How do I deal with having some set by command line arguments some of the time?
有时我如何处理通过命令行参数设置的某些内容?
I don't have enough reputation points to answer my own question. However, I have a solution:
我没有足够的声望点来回答我自己的问题。但是,我有一个解决方案:
Override a variable in a Bash script from the command line
#!/bin/bash
a=input1
b=input2
c=input3
while getopts "a:b:c:" flag
do
case $flag in
a) a=$OPTARG;;
b) b=$OPTARG;;
c) c=$OPTARG;;
esac
done
回答by codeape
You can do it the following way. See Shell Parameter Expansionon the Bash man page.
您可以通过以下方式进行。请参阅Bash 手册页上的Shell 参数扩展。
#! /bin/bash
value=${1:-the default value}
echo value=$value
On the command line:
在命令行上:
$ ./myscript.sh
value=the default value
$ ./myscript.sh foobar
value=foobar
回答by nosid
Instead of using command line arguments to overwrite default values, you can also set the variables outside of the script. For example, the following script can be invoked with foo=54 /tmp/foobaror bar=/var/tmp /tmp/foobar:
您还可以在脚本之外设置变量,而不是使用命令行参数来覆盖默认值。例如,可以使用foo=54 /tmp/foobar或调用以下脚本bar=/var/tmp /tmp/foobar:
#! /bin/bash
: ${foo:=42}
: ${bar:=/tmp}
echo "foo=$foo bar=$bar"

