首页 > 解决方案 > shift 和 getopts

问题描述

我正在使用getopts并打算使用-v可以采用可选参数的选项。

当使用getoptisstead of 时getopts,人们习惯使用shift命令转到下一个参数。但我没有看到人们在使用shift时使用getopts.

 local vb=1  sort=0

 local OPTIND OPTARG
 local shortopts="Vuhvs"
 while getopts $shortopts arg; do
   case $arg in
     ("V") printf '%s\n' "Version" ; return ;;
     ("u") printf '%s\n' "usage"   ; return ;;
     ("h") printf '%s\n' "help"    ; return ;;
     ("v")
       # Allows argument to be optional.
       # Defines option with no arguments in shortopts.
       nextarg=${!OPTIND}
       if [[ (-n "$nextarg") && ("$nextarg" != -*) ]] ; then
         OPTIND=$((OPTIND + 1))
         vb="$nextarg"
       fi
       ;;
     #.............................
     ("s") sort=1 ; shift ;;         # shifts arg by 1
     #.............................
     (?)
       pfm "Invalid option: -${OPTARG}."
       pfm "Invoke \`linge-pfa -h\` for details."
       break
       ;;
   esac
 done

标签: bashgetopts

解决方案


推荐阅读