解析命令行参数并编写有用的使用消息,无需额外代码[重复]

问题描述 投票:0回答:1

这与其说是一个问题,不如说是一个提示: 目标是解析命令行创建有用的用法消息

代码:

for arg ; do
  case "$arg" in
    --edit)   # edit file
              cd "$(dirname $0)" && vim "$0"
    ;;
    --noN)    # do NOT create 'NHI1/../tags'
              let noN=1
    ;;
    --noS)    # do NOT create 'HOME/src/*-latest/tags'
              let noS=1
    ;;
    --help)   # write this help message
    ;&
    *)        echo "usage: $(basename $0) options..." 1>&2
              awk '/--?\w+\)/' "$0"  1>&2
              exit
    ;;
  esac
done

这将创建 usage 消息:

> build_tags.bash -x
usage: build_tags.bash options...
    --edit)   # edit file
    --noN)    # do NOT create 'NHI1/../tags'
    --noS)    # do NOT create 'HOME/src/*-latest/tags'
    --help)   # write this help message

线索是 case 目标的 definition 也是 case 目标的 documentation

bash command-line command-line-arguments
1个回答
-2
投票

最初的描述已经有所需的答案。

  • 使用 awk 直接从 case 语句解析选项。
© www.soinside.com 2019 - 2024. All rights reserved.