Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment variable value by 1 (shell programming)

I am a beginner in shell programming, and it sounds like a very stupid question but 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??

like image 409
Computernerd Avatar asked Jan 10 '14 02:01

Computernerd


People also ask

How do you increment a variable value in shell?

Using + and - Operators The most simple way to increment/decrement a variable is by using the + and - operators. This method allows you increment/decrement the variable by any value you want.

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

A program can increment by 1 the value of a variable called c using the increment operator, ++, rather than the expression c=c+1 or c+=1. An increment or decrement operator that is prefixed to (placed before) a variable is referred to as the prefix increment or prefix decrement operator, respectively.

How do you increment a variable by one in bash?

Bash has two special unary operators increment (++) and decrement (–) operators. Increment (++) operator increases the value of a variable by 1 and decrement (–) operator decreases the value of a variable by 1, and return the value.

What is if $1 in shell script?

$1 is the first command-line argument passed to the shell script. Also, know as Positional parameters. For example, $0, $1, $3, $4 and so on.


2 Answers

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++)) 
like image 92
Gabriel L. Avatar answered Sep 24 '22 13:09

Gabriel L.


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.

like image 32
Zahid Avatar answered Sep 22 '22 13:09

Zahid