我正在尝试创建一个脚本,该脚本将带有一个带有 optional 的标志。使用getopts可以在标志后指定一个强制性参数(使用冒号),但是我想使其保持可选状态。

将会是这样的:

./install.sh -a 3

或者
./install.sh -a3

其中“a”是标志,“3”是a后面的可选参数。

提前致谢。

最佳答案

getopt外部程序通过在选项名称中添加双冒号,使选项具有单个可选参数。

# Based on a longer example in getopt-parse.bash, included with
# getopt
TEMP=$(getopt -o a:: -- "$@")
eval set -- "$TEMP"
while true ; do
   case "$1" in
     -a)
        case "$2" in
          "") echo "Option a, no argument"; shift 2 ;;
          *) echo "Option a, argument $2"; shift 2;;
        esac ;;
     --) shift; break ;;
     *) echo "Internal error!"; exit 1 ;;
   esac
done

关于bash - 如何为标志创建带有可选参数的bash脚本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15524839/

10-13 07:45
查看更多