bash scripting problem

John Heim jheim at math.wisc.edu
Mon Dec 3 19:12:08 UTC 2007


Probably the easiest way to do it is

((z=$x+$y))

Double parens force mathematical evaluation in bash.


----- Original Message ----- 
From: "Geoff Shang" <Geoff at quitelikely.com>
To: "Linux for blind general discussion" <blinux-list at redhat.com>
Sent: Sunday, December 02, 2007 5:28 AM
Subject: Re: bash scripting problem


> Daniel Dalton wrote:
>
>> # !/bin/bash
>> # Print the value of 2 numbers added
>>
>> x=10
>> y=15
>> z=$x+$y
>> echo $z
>> exit 0
>>
>> I get 10 +15 as the output.
>>
>> I want to get 25.
>> What am I doing wrong?
>
> As you've noticed, $x+$y gives you "10+15".  This is because $x and $y are 
> being treated like strings, or at least the operation to assign to z 
> treats the output as a string.
>
> Despite what I wrote about expr, you can actually do it in the shell 
> itself.  You simply have to tell bash that you want the result of a 
> mathematical operation, not just a string.  So replace
>
> z=$x+$y
>
> with
>
> z=$[$x+$y]
>
> and in fact you can use
>
> z=$[x+y]
>
> and something to mess with your head.
>
>> z=x+y
>> echo $z
> x+y
>> echo $[z]
> 25
>
> Interesting.
>
> Of course, your whole script could have been executed on one line:
>
> echo $[10+15]
>
> but what you sent is presumably just an example as you could have just 
> typed
>
> echo 25
>
> One other thing.  You don't need to put the exit statement at the end of a 
> script.  Unless you're running a loop or something, a script which reaches 
> the end will just exit by itself with a 0 exit status.
>
> Hope this helps,
> Geoff (who learned a few things while writing this message).
>
> _______________________________________________
> Blinux-list mailing list
> Blinux-list at redhat.com
> https://www.redhat.com/mailman/listinfo/blinux-list
>
> 




More information about the Blinux-list mailing list