如何在 shell 脚本中获取可选参数。
block 引用>Command Line argument would be: ./abc.sh parm1 parm2 parm3 parm4
这里 parm3 和 parm4 是可选的,具体取决于 parm1(config)
How to write a shell script which will take mandatorily parm1 and parm2 as argument and treat the other two as optional parameters
最佳答案
对所需参数使用 ${var?}
语法:
#!/bin/sh
: ${1:?first argument is required}
: ${2:?second argument is required}
您可以使用 $#
检查参数数量,这样您就可以执行以下操作:
#!/bin/sh
die() { echo "$@" >&2; exit 1; }
case ${1?} in
foo) test $# = 4 || die When first argument is foo, you must give 4 args;;
bar) test $# = 2 || die When first argument is bar, only give 2 args;;
*) ;;
esac
关于linux - 接受可选参数的 Shell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32323925/