Increment variable value by 1 ( shell programming)

佐手、 提交于 2020-04-29 07:19:29

问题


I am a beginner to shell programming and it sounds like a very stupid question but i cant seem to be able to increase the variable value by 1. I have looked at tutorial but it only shows how to add together 2 variables

I have tried the following methods but it doesnt work

i=0

$i=$i+1 # doesnt work , command not found

echo "$i"

$i='expr $i+1' # doesnt work , command not found

echo "$i"

$i++ # doesnt work , command not found

echo "$i"

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


回答1:


You can try this :

i=0
i=$((i+1))



回答2:


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.




回答3:


The way to use expr:

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

the way to use i++

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

Tested in gnu bash




回答4:


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.




回答5:


you can use bc as it can also do floats

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


来源:https://stackoverflow.com/questions/21035121/increment-variable-value-by-1-shell-programming

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!