I try to implement positional parameters in bash script and check them, but have some issue in if/then switch statement.
Script:
#set "default" parameter
query=""
while [ "$1" != "" ]; do
case $1 in
-q | --query ) shift
query=$1
;;
esac
shift
done
#query cannot be empty
if (($query == ""))
then
echo 'no query'
exit
fi
echo "query - $query"
All works well when I set the correct parameters:
$ ./script.sh -q request
query - request
-q
parameter cannot be empty and I need to validate it. So, when the command line looks like:
$ ./script.sh -q
or
$ ./script.sh
I get this error:
./main.sh: line 13: ((: == : syntax error: operand expected (error token is "== ")
query -
How to correctly implement if
operator in this case?
(( ... ))
is for arithmetic evaluation.You should use
[ ... ]
(just like you did in thewhile
condition) or bash's extended test syntax[[ ... ]]
- and remember to quote "$query" and leave whitespace around the[
and]
operators:Alternatively, use the
-z
empty string test:For general help with questions like this, try www.shellcheck.net or install the
shellcheck
package from theuniverse
repository.