LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Help need for shell script (https://www.linuxquestions.org/questions/linux-newbie-8/help-need-for-shell-script-938373/)

maneshmotts 04-05-2012 06:30 PM

Help need for shell script
 
HI ,

I need help regarding the shell scripting . I used the following commands on Centos flavoured linux

Code:

x=1000
y=1
expr x / y

when is user expr it showed the following error
Quote:

"expr: non-numeric argument"
I needed your guys help in fix this error.

Thanks.

PTrenholme 04-05-2012 07:09 PM

Try expr ${x} / ${y} . Without the $ "x" means a literal x, the $x (or, pedantically, ${x}) means "the value of the variable x.

Here's an example:
Code:

$  x=1000;y=1;expr ${x} / ${y}; expr ${y} / ${x}
1000
0

Note that the value of y/x = 0 is the correct answer. That's because bash arithmetic is "integer values only."

By the way, the expr command is not really necessary. Consider this:
Code:

$ x=1000;y=1;echo $((${x} / ${y}));echo $((${y} / ${x}))
1000
0

Or this one:
Code:

$ x=1000;y=1;echo "scale=3;${x} / ${y}" | bc;echo "scale=3;${y} / ${x}" | bc
1000.000
.001

See info bash, info expr and info bc for details.

David the H. 04-06-2012 12:53 PM

This page should give you all you need to know about doing integer arithmetic in the shell:

http://mywiki.wooledge.org/ArithmeticExpression

There's also a link on that page to another one describing how to do floating-point math. Floating point nearly always requires an external tool.

And as pointed out, expr is pretty much completely superfluous these days. It's probably best to just forget that it exists at all.

(Actually, it does have one or two other features that can still come in handy, but only on very rare occasions. You certainly don't need it for doing math.)

grail 04-06-2012 01:23 PM

I thought I would add to the following example by David:
Quote:

$ x=1000;y=1;echo $((${x} / ${y}));echo $((${y} / ${x}))
And say that when using the round brackets the dollar symbols for variables is also not required:
Code:

$ x=1000;y=1;echo $(( x / y ));echo $(( y / x ))
1000
0


maneshmotts 04-06-2012 01:38 PM

Thanks guys it help me a lot . Thank you so much !!!

grail 04-07-2012 03:53 AM

Please mark as SOLVED once you have a solution


All times are GMT -5. The time now is 07:16 PM.