我正在写一个bash脚本,用像这样的getoptsparsing选项:
#!/bin/bash while getopts ab: ; do case $opt in a) AOPT=1 ;; b) BOPT=$OPTARG ;; esac done
我想有“-b”选项OPTIONALLY采取一个参数,但事实是,如果没有parameter passinggetopts抱怨。 我怎样才能做到这一点?
谢谢!
您可以通过在冒号模式下运行getopts,将冒号作为optstring的第一个字符。 这可以用来抑制错误消息。
从getopts手册页:
If the first character of optstring is a colon, the shell variable specified by name shall be set to the colon character and the shell variable OPTARG shall be set to the option character found.
因此,类似以下的东西可能适合你:
#!/bin/bash AOPT="unassigned" BOPT="unassigned" while getopts :ab: opt ; do case $opt in a) AOPT=1 ;; b) BOPT=$OPTARG ;; :) BOPT= ;; esac done echo "AOPT = $AOPT" echo "BOPT = $BOPT"
一些例子:
rlduffy@hickory:~/test/getopts$ ./testgetopts -a -b Hello AOPT = 1 BOPT = Hello rlduffy@hickory:~/test/getopts$ ./testgetopts -b goodbye AOPT = unassigned BOPT = goodbye rlduffy@hickory:~/test/getopts$ ./testgetopts -a -b AOPT = 1 BOPT =