Do shell scripts permit arithmetic operations?
Hi.
In a language such as C or something you can define a variable to be of type double, say, and then go on and perform numerical operations involving this variable. result=var*3.14 for example, where result would be defined to be of type double also. Are such operations possible within shell scripts? I've defined a variable $norm to represent the number of seconds in a day in a bash script: norm=24*60*60 But then just to check everything was as it should be I echoed the variable norm to the screen ( echo $norm ) and it gave me: > 24*60*60 I have a bit of simple multiplying and dividing to do involving variables...is this possible within shell scripts? Thanks |
Yes, you can use:
(( norm = 24*60*60 )) or let "norm=24*60*60" |
Thanks for that.
But do you know if everything is treated as type double or what? eg if a & b were defined as type int and were assigned: a=5 b=2 then a/b=2 in other languages Are there type definitions in scripting or is it handled automatically somehow? |
Integers and strings only. You do not need a type definition:
darktown:~ # (( norm=5/2 )) darktown:~ # echo $norm 2 darktown:~ # VAR="some text" darktown:~ # echo $VAR some text darktown:~ # VAR=11/2 darktown:~ # echo $VAR 11/2 darktown:~ # (( VAR = 11/2 )) darktown:~ # echo $VAR 5 darktown:~ # (( VAR = 11%2 )) darktown:~ # echo $VAR 1 The % operator is for modulo. If you need floating point, bash is not what you need. |
ok. that's cleared it up. Thanks.
|
bash doesn't have an internal mechanism to do floating point arithmetic. The $((expression)) syntax only does integer math.
You can always put a command through bc -l using the `backtick execution` syntax (or $(like this) if you prefer - as I do): Code:
$ result=$(echo "3.14159265359 / 2" | bc -l) |
Just to mention, you can use something like this too:
Code:
$ expr 1 + 1 |
All times are GMT -5. The time now is 09:36 AM. |