113

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?

4
  • assignments to variables won't have the leading $ character on the LHS of the expression. Commented Jan 10, 2014 at 2:29
  • 1
    How to increment a variable in bash? Commented Sep 25, 2018 at 9:59
  • 2
    for the expr one, it's not working because they have to be backticks ( ` ) rather than single quotes ( ' ) Commented Feb 3, 2020 at 18:28
  • (only shows how to add together two variables - well, they show assignment of a sum of literals: val=`expr 2 + 2`.) Commented Apr 11, 2021 at 15:20

5 Answers 5

197

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++))
Sign up to request clarification or add additional context in comments.

2 Comments

The first variant also works in dash (which is sh on many systems). The two others do not.
The two others are not POSIX compliant - I think they are bash only. So stick to the first one for maximum portability.
15

The way to use expr:

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

The way to use i++ (unless you're running with -e/-o errexit):

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

Tested in gnu bash.

Comments

4

you can use bc as it can also do floats

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

Comments

0

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.

Comments

0

Here is an explicit way:

i=0 # initialize the variable to your liking
echo $i # inspect the value
let 'i=i+1' # increment by one
echo $i # inspect the value again

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.