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@xxxxxxxxxx
https://www.redhat.com/mailman/listinfo/blinux-list