在bash脚本中解析参数的最佳方法
所以我一直在阅读有关getopts、getopt等的内容,但我还没有找到解决问题的确切方法 使用我的脚本的基本思想是:在bash脚本中解析参数的最佳方法,bash,command-line-arguments,getopt,getopts,Bash,Command Line Arguments,Getopt,Getopts,所以我一直在阅读有关getopts、getopt等的内容,但我还没有找到解决问题的确切方法 使用我的脚本的基本思想是: ./program [-u] [-s] [-d] <TEXT> 然后程序将不会意识到使用不正确 我最接近的方法是使用getopt和IFS ARGS=$(getopt usd: $*) IFS=' ' read -a array <<< "$ARGS" ARGS=$(getopt usd:$*) IFS=''read-a array这是我通常做的
./program [-u] [-s] [-d] <TEXT>
然后程序将不会意识到使用不正确
我最接近的方法是使用getopt和IFS
ARGS=$(getopt usd: $*)
IFS=' ' read -a array <<< "$ARGS"
ARGS=$(getopt usd:$*)
IFS=''read-a array这是我通常做的:
local badflag=""
local aflag=""
local bflag=""
local cflag=""
local dflag=""
while [[ "$1" == -* ]]; do
case $1 in
-a)
aflag="-a"
;;
-b)
bflag="-b"
;;
-c)
cflag="-c"
;;
-d)
dflag="-d"
;;
*)
badflag=$1
;;
esac
shift
done
if [ "$badflag" != "" ]; do
echo "ERROR CONDITION"
fi
if [ "$1" == "" ] && [ "$dflag" == "" ]; do
echo "ERROR CONDITION"
fi
local remaining_text=$@
使用getopts
非常简单:
#!/bin/bash
u_set=0
s_set=0
d_set=0
while getopts usd OPT; do
case "$OPT" in
u) u_set=1;;
s) s_set=1;;
d) d_set=1;;
*) # getopts produces error
exit 1;;
esac
done
if ((!d_set && OPTIND>$#)); then
echo You must provide text or use -d >>/dev/stderr
exit 1
fi
# The easiest way to get rid of the processed options:
shift $((OPTIND-1))
# This will run all of the remaining arguments together with spaces between them:
TEXT="$*"
命令行参数通常是短字符串。考虑从标准输入中获得“<代码> <代码> >。在引用的示例中,用法是如何错误的?正确的输入是什么?可能与、、等重复。这样做的(缺点)是不能将单个字母选项组合在一起;必须单独明确使用每个选项,并在脚本的下一个参数中使用任何选项参数。因此,您不能模拟ls-ls
,或sort-ooput
,而使用getopts
,您可以。
#!/bin/bash
u_set=0
s_set=0
d_set=0
while getopts usd OPT; do
case "$OPT" in
u) u_set=1;;
s) s_set=1;;
d) d_set=1;;
*) # getopts produces error
exit 1;;
esac
done
if ((!d_set && OPTIND>$#)); then
echo You must provide text or use -d >>/dev/stderr
exit 1
fi
# The easiest way to get rid of the processed options:
shift $((OPTIND-1))
# This will run all of the remaining arguments together with spaces between them:
TEXT="$*"