shelldebuggingvariablesubuntucommand-line

Increment variable value by 1 (shell programming)


I can't seem to be able to increase the variable value by 1. I have looked at tutorialspoint's Unix / Linux Shell Programming tutorial but it only shows how to add together two variables.

I have tried the following methods but they don't work:

i=0

$i=$i+1 # doesn't work: command not found

echo "$i"

$i='expr $i+1' # doesn't work: command not found

echo "$i"

$i++ # doesn't work*, command not found

echo "$i"

How do I increment the value of a variable by 1?


Solution

  • You can use an arithmetic expansion like so:

    i=$((i+1))
    

    or declare i as an integer variable and use the += operator for incrementing its value.

    declare -i i=0
    i+=1
    

    or use the (( construct.

    ((i++))