Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer addition in shell

Tags:

linux

bash

shell

Here is my simple shell code. I want the result to be 2.Shell treats everything as a string. How can i get this done ?

num=1
num=$(( $num + 1 ))

EDIT :

Complete code : Whats wrong in this if i want to print from 1 to 10 ?

#! /bin/bash

num=1
until test $num -eq 10
do
    num=$(( $num + 1 ))
    echo $num
done
like image 725
Jaseem Avatar asked Jan 04 '12 08:01

Jaseem


People also ask

What does $() mean in shell script?

$() – the command substitution. ${} – the parameter substitution/variable expansion.


4 Answers

In bash, you don't need to do anything special:

aix@aix:~$ num=1
aix@aix:~$ num=$(( $num + 1 ))
aix@aix:~$ echo $num
2
like image 101
NPE Avatar answered Oct 28 '22 12:10

NPE


@tonio; please don't advocate using subshell (` ... or $( ... ) ) constructs when they're not needed (to keep confusion to the maximum, $(( ... )) is not a sub-shell construct). Sub-shells can make a tremendous performance hit even with rather trivial amounts of data. The same is true for every place where an external program is used to do somethign that could be done with a shel built-in.

Example:

    num=1
    time while [[ $num -lt 10000 ]]; do
            num=$(( num+1 ))
    done
    echo $num
    num=1
    time while /bin/test $num -lt 10000; do
            num=$( /bin/expr $num + 1 )
    done
    echo $num

Output (run in ksh on Linux):

real    0m0.04s
user    0m0.04s
sys     0m0.01s
10000

real    0m20.32s
user    0m2.23s
sys     0m2.92s
10000

...so run-time factor of 250, and CPU-time factor of 100. I admit the example I used was a exaggerated one, with explicitly requiring all built-ins to be bypassed, but I think the point was made: creating new processes is expenisve, avoid it when you can, and know your shell to recognise where new processes are created.

like image 32
Juha Laiho Avatar answered Oct 28 '22 14:10

Juha Laiho


This might work for you:

num=1; ((num++)); echo $num
2

or

num=1; echo $((++num))
2

for loops

for num in {1..10}; do echo $num; done

or (in bash at least)

for ((num=1; num<=10; num++)) { echo $num; }

second loop more useful when more programming involved:

for (( num=1,mun=10; num<=10; num++,mun--)) { echo $num $mun; }
like image 34
potong Avatar answered Oct 28 '22 14:10

potong


You just did:

$ num=1; num=$(( $num + 1 ));echo $num
2

Note: You don't need to quote variables inside $(( )). Also, you can just use $((num++))

like image 43
SiegeX Avatar answered Oct 28 '22 14:10

SiegeX