I have tried to increment a numeric variable using both var=$var+1
and var=($var+1)
without success. The variable is a number, though bash appears to be reading it as a string.
Bash version 4.2.45(1)-release (x86_64-pc-linux-gnu) on Ubuntu 13.10.
There is more than one way to increment a variable in
bash
, but what you tried will not work.You can use, for example, arithmetic expansion:
Or you can use
let
:See also: https://tldp.org/LDP/abs/html/dblparens.html.
Arithmetic in bash uses
$((...))
syntax.Various options to increment by 1, and performance analysis
Thanks to Radu Rădeanu's answer that provides the following ways to increment a variable in bash:
There are other ways too. For example, look in the other answers on this question.
Having so many options leads to these two questions:
Incremental performance test code:
Results:
Conclusion:
It seems bash is fastest at performing
i+=1
when$i
is declared as an integer.let
statements seem particularly slow, andexpr
is by far the slowest because it is not a built into bash.There's also this:
Take careful note of the spaces and also ` is not '
While Radu's answers, and the comments, are exhaustive and very helpful, they are bash-specific. I know you did specifically ask about bash, but I thought I'd pipe in since I found this question when I was looking to do the same thing using sh in busybox under uCLinux. This portable beyond bash.
If you declare
$var
as an integer, then what you tried the first time will actually work:Reference: Types of variables, Bash Guide for Beginners
There's one method missing in all the answers -
bc
bc
is specified by POSIX standard, so should be present on all versions of Ubuntu and POSIX-compliant systems. The<<<
redirection could be altered toecho "$VAR" | bc
for portability, but since the question asks aboutbash
- it's OK to just use<<<
.The return code
1
issue is present for all default variants (let
,(())
, etc.). This often causes trouble, e.g., in scripts that useset -o errexit
. Here is what I am using to prevent error code1
from math expressions that evaluate to0
;This has to be the worst way to accomplish such a simple task but I just wanted to document it for fun I guess (complete opposite of code golf).
or
Seriously use one of the other much better choices here.
This is the safe bet
If the resulting value is non zero, then setting exit on error will stop Your script