简体   繁体   English

如何在bash中首先以任何带有长可选或非可选参数的随机顺序使用getopts?

[英]How to use getopts in any random order with long optional or non-optional argument first in bash?

I have a script like 我有一个像

./sample.sh --add employeename -f firstname -a age -d detail
./sample.sh --add employeename  -a age -d detail -f firstname
./sample.sh --add employeename -d detail -f firstname
./sample.sh --del employeename
./sample.sh --update employeename -f firstname [age,detail are optional]

here,how could i use getopts for --add, --del, --update and i don't want to use getopt. 在这里,我怎么能对--add,--del,--update使用getopts而我不想使用getopt。 Good suggestion will be appreciated. 好的建议将不胜感激。

Those are really commands, not options, so should be regular positional arguments: 这些实际上是命令,而不是选项,因此应该是常规的位置参数:

./sample.sh add employeename -f firstname -a age -d detail
./sample.sh add employeename  -a age -d detail -f firstname
./sample.sh add employeename -d detail -f firstname
./sample.sh del employeename
./sample.sh update employeename -f firstname [age,detail are optional]

which should come first; 应该先到 then the remaining options can be parsed using a command-specific set of options. 然后可以使用特定于命令的选项集来解析其余选项。

cmd=$1
shift
case $cmd in
  add) do_add "$@" ;;
  del) do_del "$@" ;;
  update) do_update "$@" ;; 
  *) echo "Unrecognized command: $cmd"
     exit 1
     ;;
esac

do_add () {
    name=$1
    shift
    while getopts "f:a:d:" opt "$@"; do
      ...
    done
    ...
}

do_del () {
    ...
}

# etc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM