bash 如果没有传递参数,如何显示帮助文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16120622/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to show help text if no arguments are passed
提问by user2298964
I've been using getopts recently and I've set everything up. I've got a problem though. I want it to work so that if someone doesn't enter an argument on the command line, they get the help text, e.g.:
我最近一直在使用 getopts 并且我已经设置好了一切。我有一个问题。我希望它能够工作,以便如果有人没有在命令行上输入参数,他们会得到帮助文本,例如:
$ ./script
$ help: xyz - argument must be used.
Here's what I have at the moment.
这就是我目前所拥有的。
#!/bin/bash
function helptext {
# ...
}
function mitlicense {
# ...
}
while getopts "hl" opt; do
case $opt in
h) helptext >&2
exit 1
;;
l) mitlicense >&2
exit 0
;;
\?) echo "Invalid option: -$OPTARG" >&2
exit 1
;;
:) echo "Option -$OPTARG requires an argument." >&2
exit 1
;;
*) helptext >&2
exit 1
;;
esac
done
回答by suspectus
Validate user input using an if test such as below.
使用如下所示的 if 测试验证用户输入。
The -zoption of testreturns true if the length of the string which follows -z is zero.
所述-z的选项test返回true,如果下面的-z串的长度是零。
if [ -z "" ]
then
helptext
exit 1
fi
回答by Gilles Quenot
Try using this in your script :
尝试在您的脚本中使用它:
#!/bin/bash
[[ $@ ]] || { helptext; exit 1; }
# --- the rest of the script ---
The line of code is the boolean shortened version of
这行代码是布尔值的缩短版本
if [[ $@ ]]; then
true
else
helptext
exit 1
fi
$@is all the arguments of the script
$@是脚本的所有参数
[[ $var ]]
is a shorthand for
是一个简写
[[ -n $var ]]
See http://mywiki.wooledge.org/BashGuide/TestsAndConditionals
请参阅http://mywiki.wooledge.org/BashGuide/TestsAndConditionals
回答by mklement0
Gilles Quenot's answerworks great and is very concise; if you're looking for solutions that express the intent more explicitly, you can try these, which are based on the countof parameters, $#:
Gilles Quenot 的回答非常有效,而且非常简洁;如果您正在寻找更明确地表达意图的解决方案,您可以尝试这些基于参数计数的解决方案$#:
[[ $# -gt 0 ]] || { helptext; exit 1; }
Alternative, using arithmetic expressions:
替代方法,使用算术表达式:
(( $# > 0 )) || { helptext; exit 1; }
Finally, shorthand that relies on 0 evaluating to false, and any non-zero number to true:
最后,依赖于 0 评估为假,任何非零数字为真的速记:
(( $# )) || { helptext; exit 1; }
William Purselloffers another variant, which is both descriptive and POSIX-compliant:
William Pursell提供了另一种变体,它既是描述性的又是符合 POSIX 的:
test $# -gt 0 || { helptext; exit 1; }
test/ [ ... ]is a POSIX utility/built-in, whereas the similar [[ ... ]]conditional is bash-specific (as is (( ... ))).
Generally, however, bash's [[ ... ]]offers more features and has fewer surprises than test/ [...].
test/[ ... ]是 POSIX 实用程序/内置,而类似的[[ ... ]]条件是bash-specific(原样(( ... )))。
然而,一般来说,bash's[[ ... ]]比test/提供更多的功能并且有更少的惊喜[...]。

