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
$() – the command substitution. ${} – the parameter substitution/variable expansion.
In bash
, you don't need to do anything special:
aix@aix:~$ num=1
aix@aix:~$ num=$(( $num + 1 ))
aix@aix:~$ echo $num
2
@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.
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; }
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++))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With