I try to implement positional parameters in bash script and check them, but have some issue in if/then switch statement.


#set "default" parameter

while [ "$1" != "" ]; do
    case $1 in
        -q | --query )          shift

#query cannot be empty
if (($query == ""))                               
 echo 'no query'

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


$ ./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?

  • 1
    This script lacks a shebang. – dessert Nov 15 '18 at 22:29
  • Who and why lowered my question ?? – Valentyn Hruzytskyi Nov 15 '18 at 22:40
  • @wjandrea, thanks. Comments I did edit. But all this code I need to put, because if statement have different error in different parameters in command line (if parameter exist - I did not get an error in if... line), so I showed all. – Valentyn Hruzytskyi Nov 15 '18 at 23:06
  • The edits are a huge improvement, thanks. I've deleted my earlier comment. – wjandrea Nov 15 '18 at 23:15

(( ... )) is for arithmetic evaluation.

You should use [ ... ] (just like you did in the while condition) or bash's extended test syntax [[ ... ]] - and remember to quote "$query" and leave whitespace around the [ and ] operators:

if [ "$query" == "" ]

Alternatively, use the -z empty string test:

if [ -z "$query" ]

For general help with questions like this, try www.shellcheck.net or install the shellcheck package from the universe repository.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.