我有一些bash代码,它似乎无法运作,我无法弄清楚原因。 if语句有问题,但我无法理解它。
function param_err_non {
echo "error: parameter missing"
return 1
}
function param_err_many {
echo "error: too many parameters"
return 1
}
function param_err_invl {
echo "error: invalid parameter"
return 1
}
dbcmd=""
dbusr=""
dbste="" #this isn't so obvious, it's the site name
dbkey=""
dbval=""
nopar=0
if [ "$1" = "" ]; then param_err_non; fi
case "$1" in
get)
dbcmd=$1
;;
put)
dbcmd=$1
;;
del)
dbcmd=$1
;;
new)
dbcmd=$1
;;
list)
dbcmd=$1
nopar=1
;;
*)
param_err_invl
esac
echo "running command $dbcmd"
if [ "$dbcmd" = "" ]; then param_err_non; fi
if [ "$2" = "" ]; then param_err_non; else dbusr=$2; fi
if [ $nopar -eq 0 ]; then
if [ "$3" = "" ]; then param_err_non; else dbste=$3; fi
fi
counter=
for param in "$@"
do
let counter=counter+1
if [ "$dbcmd" = "del" ]; then
echo "entering delete param check $counter"
if [ "$3" = "" ]; then deleteall=1; else
if [ $counter -eq 4 ]; then param_err_many; fi
fi
fi
if [ "$dbcmd" = "get" ]; then
if [ $counter -eq 4 ]; then dbkey="$4"; fi
if [ $counter -ge 5 ]; then param_err_many; fi
fi
if [ "$dbcmd" = "put" ]; then
if [ $counter -eq 4 ]; then dbkey="$4"; fi
if [ $counter -eq 5 ]; then dbval="$5"; fi
if [ $counter -ge 6 ]; then param_err_many; fi
fi
if [ "$dbcmd" = "new" ]; then
if [ $counter -eq 4 ]; then param_err_many; fi
fi
if [ "$dbcmd" = "list" ]; then
if [ $counter -eq 4 ]; then param_err_many; fi
fi
done
我得到的输出如下......
$ source db-scripts/sitedb.bash del john thirdtest
running command del
entering delete param check 1
entering delete param check 2
entering delete param check 3
bash: [: =: unary operator expected
error: parameter missing
我真的只需要额外的一双眼睛,因为有问题的if语句似乎都很好。
答案 0 :(得分:1)
问题是类似于以下几行的问题之一:
if [ $counter -eq 4 ]; then param_err_many; fi
修复方法是将变量括在双引号中 - "$counter"
,或者将计数器初始化为0而不是空字符串。
如果这不能解决问题,那么您应该在问题中出现错误的位置附近运行bash -x yourscript.sh
的调试输出。事实上,在将来,如果shell中出现异常,首先要做的是使用bash -x
运行它以查看出现了什么问题。