I need to have two variables and want to perform an addition with these variables in shell script.

I am using the below script for this, but I get an expr: non-numeric argument error while running the same.

#!/bin/sh
val1=10
val2=20
while [val1 -gt 5]
do
echo $val1
val1=$(expr $VAL + $BAL)
done
link|improve this question

60% accept rate
feedback

1 Answer

up vote 2 down vote accepted

This is wrong:

while [val1 -gt 5]

It should be:

while [ $val1 -gt 5 ]

… because:

  • You need the dollar sign in $val1 to refer to the variable.
  • You need a space between the bracket [ and the variable. It's a command, and otherwise the shell would first expand $val1 to its value 10 and then would search for the command [10, which it obviously can not find.

Apart from that, your script should work in theory, but neither $VAL nor $BAL are defined, so it's understandable that you get an error.

link|improve this answer
Thanks for the clarification. Will this script work fine if i replace $VAL and $BAL with $val1 and $val2 – Vel Dec 24 '11 at 18:11
Yes. Although it doesn't make a lot of sense because the loop will never exit ;) – slhck Dec 24 '11 at 18:14
Oops! As i am newbie to shell scripting, i was trying an arithmetic operation. Its really exciting!! – Vel Dec 24 '11 at 18:23
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.