如何添加到您的 bash 脚本帮助选项"yourscript --help"



是否有可能在Linux(Debian)中为bash脚本添加"帮助"?我的意思是,通过使用命令yourscript --helpyourscript -h

没有比这更难的了。

case $1 in
 -[h?] | --help)
    cat <<-____HALP
        Usage: ${0##*/} [ --help ]
        Outputs a friendly help message if you can figure out how.
____HALP
        exit 0;;
esac

如果您使用getopts进行选项处理,请使用它来识别选项;但是动作看起来或多或少是相似的(并且IMNSHO getopts在简单的while ... shift循环上并没有真正提供任何东西)。

getopt

#!/bin/bash
args=$(getopt -n "$(basename "$0")" -o h --longoptions help -- "$@") || exit 1
eval set -- "$args"
while :; do
    case $1 in
        -h|--help) echo offer help here ; exit ;;
        --) shift; break ;;
        *) echo "error: $1"; exit 1;;
    esac
done
echo "hello world, $*"

有很多方法可以做到这一点。随着时间的推移,我越来越喜欢单独的usagehelp函数。help是响应于对--help-h的请求而提供的,并且它以heredoc格式提供扩展的帮助/选项信息。usage功能是响应于无效输入而提供的。它很短,可以快速提醒您脚本需要什么。这两个函数都将字符串作为第一个参数,允许您传递将与helpusage一起显示的错误消息。两者都允许您传递一个exit code作为第二个参数。

下面是我从现有脚本中提取的一个示例。你可以忽略内容,但它是通过示例的方式留下的:

function help {
  local ecode=${2:-0}
  [[ -n $1 ]] && printf "n $1n" >&2
cat >&2 << helpMessage
  Usage: ${0##*/} <ofile> <file.c> [ <cflags> ... --log [ $(<./bldflags)]]
    ${0##*/} calls 'gcc -Wall -o <ofile> <file.c> <cflags> <$(<./bldflags)>'
    If the file './bldflags' exists in the present directory, its contents are
    read into the script as additional flags to pass to gcc. It is intended to
    provide a simple way of specifying additional libraries common to the source
    files to be built. (e.g. -lssl -lcrypto).
    If the -log option is given, then the compile string and compiler ouput are
    written to a long file in ./log/<ofile>_gcc.log
  Options:
    -h  |  --help  program help (this file)
    -l  |  --log   write compile string and compiler ouput to ./log/<ofile>_gcc.log
helpMessage
  exit $ecode
}
function usage {
  local ecode=${2:-0}
  [[ -n $1 ]] && printf "n $1n" >&2
  printf "n  Usage: %s <ofile> <file.c> [ <cflags> ... --log [ $(<./bldflags)]]nn" "${0##*/}"
  exit $ecode
}

我通常在查看所有参数时测试help,例如:

## test for help and log flags and parse remaining args as cflags
for i in $*; do
    test "$i" == "-h" || test "$i" == "--help" && help
    ...
done

使用是为了响应无效输入而提供的,例如:

[ -f "$1" ] || usage "error: first argument is not a file." 1

它们派上了用场,我更喜欢这种方法而不是getopts

最新更新