Search code examples
shellscriptingadditionshortcutassignment-operator

Shell Script : shortcut add and assignment += : command not found


Using Mac Terminal and Shell Script

Trying to do Shortcut of add and assignment operator like

SumVar=1

$(( SumVar += 5 ))

echo $SumVar

Getting error :

Error: line 3: 5: command not found

What is the correct syntax of this ?


Solution

  • Your syntax for incrementing the variable is correct, but you are using it in a context where Bash wants a command, and it complains that the result of the increment (4) is not a recognized command.

    The let keyword is your friend.

    let SumVar+=4
    

    Or better yet just leave out the dollar sign (thanks @chepner);

    (( SumVar += 4 ))