Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
share|improve this question
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.

share|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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .