Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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

1 Answer 1

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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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