如何编写带有可选输入参数的 bash 脚本? [英] How to write a bash script that takes optional input arguments?
问题描述
我希望我的脚本能够接受可选输入,
I want my script to be able to take an optional input,
例如目前我的脚本是
#!/bin/bash
somecommand foo
但我想说:
#!/bin/bash
somecommand [ if $1 exists, $1, else, foo ]
推荐答案
你可以使用默认值语法:
You could use the default-value syntax:
somecommand ${1:-foo}
以上将,如Bash 参考手册中所述- 3.5.3 Shell 参数扩展 [强调我的]:
The above will, as described in Bash Reference Manual - 3.5.3 Shell Parameter Expansion [emphasis mine]:
如果参数未设置或为空,则替换单词的扩展.否则,参数的值被替换.
If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.
如果您只想在参数未设置的情况下替换默认值(但如果它为空则不替换,例如,如果它是空字符串则不替换),请改用以下语法:
If you only want to substitute a default value if the parameter is unset (but not if it's null, e.g. not if it's an empty string), use this syntax instead:
somecommand ${1-foo}
再次来自 Bash 参考手册 - 3.5.3 Shell参数展开:
省略冒号会导致仅对未设置的参数进行测试.换句话说,如果包含冒号,则运算符会测试两个参数的存在以及它的值是否不为空;如果省略冒号,则运算符仅测试存在性.
Omitting the colon results in a test only for a parameter that is unset. Put another way, if the colon is included, the operator tests for both parameter’s existence and that its value is not null; if the colon is omitted, the operator tests only for existence.
这篇关于如何编写带有可选输入参数的 bash 脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!