Linux 如何添加到bash脚本帮助选项“中”;您的脚本--“帮助”;
是否有可能将“帮助”添加到Linux(Debian)中由您编写的bash脚本中?我的具体意思是,通过使用命令Linux 如何添加到bash脚本帮助选项“中”;您的脚本--“帮助”;,linux,bash,Linux,Bash,是否有可能将“帮助”添加到Linux(Debian)中由您编写的bash脚本中?我的具体意思是,通过使用命令yourscript--help或yourscript-h,不必比这更难 case $1 in -[h?] | --help) cat <<-____HALP Usage: ${0##*/} [ --help ] Outputs a friendly help message if you can figure out how. ___
yourscript--help
或yourscript-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
案例中的$1
-[h?]|——帮助)
cat
有很多方法可以做到这一点。随着时间的推移,我越来越喜欢使用单独的用法
和帮助
功能。帮助
是响应--help
或-h
请求而提供的,它以herdoc
格式提供扩展的帮助/选项信息。用法
功能用于响应无效输入。它很短,可以快速提醒脚本需要什么。这两个函数都将字符串作为第一个参数,允许您传递错误消息,以便与帮助
或用法
一起显示。这两种方法都允许您将退出代码
作为第二个参数传递
下面是我从现有脚本中提取的一个示例。您可以忽略其中的内容,但仅作为示例:
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
}
为响应无效输入提供用法,例如:
[ -f "$1" ] || usage "error: first argument is not a file." 1
它们很方便,我更喜欢这种方法,而不是getopts
在一些高级编程语言中,有些软件包将附带帮助格式化程序,以便可以使用选项的定义生成帮助。遗憾的是,它不太适合bash。
## 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