Wednesday, February 2, 2022

[SOLVED] Bash return [: =: unexpected operator error

Issue

I just do a simple task,input a bc then if c is "+" it will print total of a+b

So i do this

echo "$a $b $c = "

if [ $c = "+" ]; then
    echo $(($a + $b))
fi

And it return simple.sh: 3: [: =: unexpected operator

What is going on?? Please help, thank a lot, im so confuse now


Solution

If $c is unset or set to nothing then the expression would expand to: [ = + ] which would cause this problem.

Always quote your parameter expansions as the result will be unexpected otherwise:

[ "$c" = "+" ]

Unquoted parameter expansions will undergo word splitting and pathname expansion.

Whenever writing shellscripts it always a good idea to use the shellcheck linter, an online version is available at https://www.shellcheck.net/



Answered By - Andreas Louv
Answer Checked By - David Marino (WPSolving Volunteer)