如何写一个bash脚本,它可选的输入参数? [英] How to write a bash script that takes optional input arguments?
问题描述
我希望我的脚本能够采取一种可选的输入,
例如。目前我的剧本
#!/斌/庆典
somecommand富
但我想它说:
#!/斌/庆典
somecommand [如果$ 1成立,$ 1,否则,富]
您可以使用默认值的语法:
somecommand $ {1:-foo}
上面的意愿,的Bash参考手册中描述 - 3.5.3壳牌参数扩展 [重点煤矿]:
如果参数没有设置的或空的,word的扩展将被替换。否则,参数的值是取代
块引用>如果您只是想替换默认值,如果该参数未设置(但如果它为空,例如不如果它是一个空字符串),使用此语法来代替:
somecommand $ {1}富
3.5.3壳牌参数扩展一 -
再从猛砸参考手册>:
省略在测试结肠结果只对一个参数没有设置。换句话说,如果在结肠中包括,这两个参数的存在,并且其值不为空操作试验;如果结肠省略,操作者测试仅对存在
块引用>I want my script to be able to take an optional input,
e.g. currently my script is
#!/bin/bash somecommand foo
but I would like it to say:
#!/bin/bash somecommand [ if $1 exists, $1, else, foo ]
解决方案You could use the default-value syntax:
somecommand ${1:-foo}
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}
Again from Bash Reference Manual - 3.5.3 Shell Parameter Expansion:
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屋!