0
#!/bin/bash
x=10
echo x=$x
z=20
echo z=$z
y= expr $x + $z
echo y=$y

I want output like :

x=10
z=20
y=30

but it gives error like:

x=10
z=20
30
y=
2
  • 1
    y=$(expr $x + $z) instead of y= expr $x + $z Commented Jan 19, 2017 at 13:31
  • 1
    y=`expr $x + $z` also works, looking for "Command Substitution in bash", is better Inian's solution way Commented Jan 19, 2017 at 13:34

1 Answer 1

5

Do NOT use the outdated construct expr, use the arithmetic operator $(()) for POSIX compliant arithmetic in bash

y=$((x + z))
echo "y=$y"
Sign up to request clarification or add additional context in comments.

2 Comments

$((...)) is not just standard, but it performs the arithmetic in the current process, rather than starting a new process to run expr.
Additionally, you could replace y=$((x + z)) with ((y = x + z)) or simply y=x+z if you declare x, y and z as integers prior with declare -i x y z

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.