Increment variable value by 1 (shell programming)

ShellDebuggingVariablesUbuntuCommand Line

Shell Problem Overview


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?

Shell Solutions


Solution 1 - Shell

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++))

Solution 2 - Shell

There are more than one way to increment a variable in bash, but what you tried is not correct.

You can use for example arithmetic expansion:

i=$((i+1))

or only:

((i=i+1))

or:

((i+=1))

or even:

((i++))

Or you can use let:

let "i=i+1"

or only:

let "i+=1"

or even:

let "i++"

See also: http://tldp.org/LDP/abs/html/dblparens.html.

Solution 3 - Shell

The way to use expr:

i=0
i=`expr $i + 1`

the way to use i++

((i++)); echo $i;

Tested in gnu bash

Solution 4 - Shell

you can use bc as it can also do floats

var=$(echo "1+2"|bc)

Solution 5 - Shell

These are the methods I know:

ichramm@NOTPARALLEL ~$ i=10; echo $i;
10
ichramm@NOTPARALLEL ~$ ((i+=1)); echo $i;
11
ichramm@NOTPARALLEL ~$ ((i=i+1)); echo $i;
12
ichramm@NOTPARALLEL ~$ i=`expr $i + 1`; echo $i;
13

Note the spaces in the last example, also note that's the only one that uses $i.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionComputernerdView Question on Stackoverflow
Solution 1 - ShellGabriel L.View Answer on Stackoverflow
Solution 2 - ShellZahidView Answer on Stackoverflow
Solution 3 - ShellBMWView Answer on Stackoverflow
Solution 4 - ShellkurumiView Answer on Stackoverflow
Solution 5 - ShellJuanRView Answer on Stackoverflow