如何添加到bash脚本帮助选项“yourscript --help”

时间:2015-03-26 18:18:23

标签: linux bash

有没有可能添加" help"你用Linux编写的bash脚本(Debian)?我的意思是,使用命令yourscript --helpyourscript -h

3 个答案:

答案 0 :(得分:1)

它并不比这更难。

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循环。)

答案 1 :(得分:1)

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, $*"

答案 2 :(得分:0)

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

以下是我从现有脚本中提取的示例。你可以忽略这些内容,但它是以举例的方式留下的:

function help {
  local ecode=${2:-0}

  [[ -n $1 ]] && printf "\n $1\n" >&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 $1\n" >&2

  printf "\n  Usage: %s <ofile> <file.c> [ <cflags> ... --log [ \$(<./bldflags)]]\n\n" "${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的这种方法。