如何在 shell 脚本中获取可选参数。
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
我是一名优秀的程序员,十分优秀!