Optional option argument with getopts

前端 未结 11 1317
while getopts \"hd:R:\" arg; do
  case $arg in
    h)
      echo \"usgae\" 
      ;;
    d)
      dir=$OPTARG
      ;;
    R)
      if [[ $OPTARG =~ ^[0-9]+$ ]];then         


        
11条回答
  •  盖世英雄少女心
    2020-11-28 08:59

    Wrong. Actually getopts does support optional arguments! From the bash man page:

    If  a  required  argument is not found, and getopts is not silent, 
    a question mark (?) is placed in name, OPTARG is unset, and a diagnostic
    message is printed.  If getopts is silent, then a colon (:) is placed in name 
    and OPTARG is set to the option character found.
    

    When the man page says "silent" it means silent error reporting. To enable it, the first character of optstring needs to be a colon:

    while getopts ":hd:R:" arg; do
        # ...rest of iverson's loop should work as posted 
    done
    

    Since Bash's getopt does not recognize -- to end the options list, it may not work when -R is the last option, followed by some path argument.

    P.S.: Traditionally, getopt.c uses two colons (::) to specify an optional argument. However, the version used by Bash doesn't.

提交回复
热议问题