LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   arithmetic in shell script (https://www.linuxquestions.org/questions/linux-newbie-8/arithmetic-in-shell-script-4175597362/)

arun natarajan 01-13-2017 02:57 AM

arithmetic in shell script
 
Hi,

Though its a simple question, am unable to find answer for this.
Expecting the value of "e" as 7.

[root@localhost ~]# cat 1.sh

a=1

b=2

c=`expr $a + $b`

d=4

e=`expr $c + $b`

echo $e
[root@localhost ~]# sh 1.sh
5
[root@localhost ~]#

astrogeek 01-13-2017 03:19 AM

Why would you expect 3 + 2 to equal 7?

pan64 01-13-2017 03:20 AM

do not use root for such a simple tests
Code:

# use
c=$(expr $a + $b)
# instead of backticks, or even better: use
c=$(( a + b ))

last but not least why do you think it should be 7? I think 5 is the correct result. Probably you mistyped: e=c+b

rtmistler 01-13-2017 07:15 AM

As stated by pan64 and astrogeek, do not use root. Another thing to do is turn on verbose output by adding a "set -xv" line near the top of your script. Also you should add a shebang line at the top of it:
Code:

#!/bin/bash

set -xv // turn on verbose debugging, comment out to remove

a=1
b=2
c=`expr $a + $b`
# d=4 commented out since it is irrelevant, however as other say, you've probably committed a typo.
e=`expr $c + $b` // This probably should be $d, correct?
echo $e

Note that for when you start to explore different forms of math, they will not work in this way, consider the bc command as well as the -l option if you wish to start performing floating point computations.

arun natarajan 01-13-2017 09:33 AM

Thanks guys.

I learnt new thing to use set -xv from you people from this post.

grail 01-13-2017 10:27 AM

Further to examples by pan64, I like to use:
Code:

(( c = a + b ))

AnanthaP 01-13-2017 10:56 AM

Arun, Did you also learn not to use root for such tasks? Or do you always login as root to avoid any permission problems?

OK


All times are GMT -5. The time now is 10:41 AM.