【发布时间】:2010-12-03 10:18:53
【问题描述】:
我创建了一个 Bash 脚本,并且我有一些相当丑陋的参数验证。我知道 getopt 和 getopts ,但认为它们是矫枉过正的。这就是我想要的用法:
Usage: flipfile [OPTION] inputfile outputfile
Options:
-f Force. Accept ANY inputfile, not just regular files.
而我目前的验证码是:
if [ $# -eq 2 ]; then
infile=$1
outfile=$2
elif [ $# -eq 3 -a $1 = "-f" ]; then
option=$1
infile=$2
outfile=$3
else
echo -e "Error. Usage: flipfile [OPTION] inputfile outputfile\n\n"
echo -e "Options:\n-f\tForce. Accept ANY inputfile, not just regular files."
exit 1
fi
验证有效。但由于我这样做是为了乐趣和学习体验,我很感激任何可以帮助我编写更清晰的 Bash 脚本的技巧。
您将如何改进此验证代码?如果您认为这是正确的决定,请使用 getopt 或 getopts。我希望可选的 -f 作为第一个参数。如果您认为[[ conditional-expression ]] 比我所拥有的更干净,也可以随意更改。我会接受我认为最干净的答案。
【问题讨论】:
标签: bash