Reputation: 772
I've got some bash code and it doesn't seem to work, and I can't figure out why. There is something wrong with an if statement, but I can't make sense of it.
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
The output I get is as follows...
$ 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
I really just need an extra set of eyes, because everything seems fine with the if statement in question.
Upvotes: 0
Views: 169
Reputation: 755104
There's a moderate chance the problem is one of the many lines similar to:
if [ $counter -eq 4 ]; then param_err_many; fi
The fix will be to enclose the variable in double quotes — "$counter"
, or to initialize the counter to 0 instead of the empty string.
If that does not solve the problem, then you should include the debug output from running bash -x yourscript.sh
around the point where the error occurs in your question. In fact, in future, if something misbehaves in the shell, the first thing to do is run it with bash -x
to see what is going wrong.
Upvotes: 1