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.

while [val1 -gt 5]
echo $val1
val1=$(expr $VAL + $BAL)

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.

  • Thanks for the clarification. Will this script work fine if i replace $VAL and $BAL with $val1 and $val2 – newbie dev 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!! – newbie dev Dec 24 '11 at 18:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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