我有这个脚本文件:
#!/bin/sh
Show_Error() {
echo -e "\033[31m ERROR \033[0m $1"
}
if [ "$1" = "-help" ]
then
echo "<input> - input file name or input URL"
else
for i in "$@"
do
case $i in
-l=*|--ddloc=*)
DDLOC="${i#*=}"
shift # past argument=value
;;
-l|--ddloc)
shift # past argument
DDLOC="$1"
shift # past value
;;
*)
# unknown option
;;
esac
done
if [ -z "$DDLOC" ]
then
Show_Error 'File is missing. Use -l or --ddloc.'
else
echo "Location::: $DDLOC"
fi
fi
如果我运行命令:
./tdl2ddlgen.sh -s sssss -m lll -l LOC
它给"Location::: sssss"
的{{1}}内嵌
答案 0 :(得分:1)
您可以考虑使用for i in "$@"
复制$@
中的所有值,然后依次将$i
设置为每个值。您可以通过检测代码来观察正在发生的事情:
for i in "$@"
do
echo "\$i = $i; \$@ = ($@)"
case $i in
# ...
给出输出:
$i = -s; $@ = (-s sssss -m 111 -l LOC)
$i = sssss; $@ = (-s sssss -m 111 -l LOC)
$i = -m; $@ = (-s sssss -m 111 -l LOC)
$i = 111; $@ = (-s sssss -m 111 -l LOC)
$i = -l; $@ = (-s sssss -m 111 -l LOC)
$i = LOC; $@ = (-m 111 -l LOC)
Location::: sssss
实际上出了问题,当您遇到未知的情况时,您并没有离开$1
选项。如果您添加班次:
for i in "$@"
do
echo "\$i = $i; \$@ = ($@)"
case $i in
-l=*|--ddloc=*)
DDLOC="${i#*=}"
shift # past argument=value
;;
-l|--ddloc)
shift # past argument
DDLOC="$1"
shift # past value
;;
*)
# unknown option
shift
;;
esac
done
然后您将获得预期的结果:
$i = -s; $@ = (-s sssss -m 111 -l LOC)
$i = sssss; $@ = (sssss -m 111 -l LOC)
$i = -m; $@ = (-m 111 -l LOC)
$i = 111; $@ = (111 -l LOC)
$i = -l; $@ = (-l LOC)
$i = LOC; $@ = ()
Location::: LOC
尽管该行为仍然不太正确-LOC
参数被处理了两次。为防止重复处理,而不是为循环复制$@
,您可以执行以下操作:
while [ -n "$1" ]
do
case $1 in
# ...