LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Do shell scripts permit arithmetic operations? (https://www.linuxquestions.org/questions/linux-newbie-8/do-shell-scripts-permit-arithmetic-operations-524060/)

johnpaulodonnell 01-30-2007 09:14 AM

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

Intec 01-30-2007 09:20 AM

Yes, you can use:
(( norm = 24*60*60 ))
or
let "norm=24*60*60"

johnpaulodonnell 01-30-2007 09:28 AM

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?

Intec 01-30-2007 09:36 AM

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.

johnpaulodonnell 01-30-2007 09:41 AM

ok. that's cleared it up. Thanks.

matthewg42 01-30-2007 10:15 AM

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)
$ echo $result
1.57079632679500000000

You could also switch shell to use zsh, which can do floating point arithmetic internally.

anupamsr 01-30-2007 10:24 AM

Just to mention, you can use something like this too:
Code:

$ expr 1 + 1
2

Though this is specific to bash probably.


All times are GMT -5. The time now is 09:36 AM.