0

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

1 Answer 1

2

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.

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

You must log in to answer this question.

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