2

Commands are..

t=20
s=$t+30

I want the output of echo $s to be 50, but I cannot figure out how to write the s= command to get it to perform addition.

Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232
Joe
  • 21
  • 1

3 Answers3

2

Shell variables are strings by default. Some shells support other variable types, but you have to let the shell know.

In any POSIX-style shell (sh except on ancient Unix systems, dash, bash, ksh, zsh, etc.), you can use arithmetic expansion to tell the shell to perform arithmetic when it's parsing the variable assignment.

t=20
s=$((t+30))
echo "$s"

(The double quotes are not necessary here, but they're a good habit to pick up.)

It's also possible to store the text of the expression to evaluate, and perform the arithmetic when printing it out.

t=20
s=$((t+30))
echo "expression: $s; evaluated: $(($s))"

But be careful with using explicit variable substitutions inside arithmetic expressions: they're substituted as text, not as arithmetic subexpressions, so operator precedence might look weird.

echo "$(($s*2))" # equivalent to $((t+30*2)), so prints 80, not 100

In bash, ksh or zsh, you can use let or ((…)) to perform arithmetic instead.

t=20
let s=t+30
echo "$s"

or

((t = 20))
((s = t + 30))
echo "$s"

or variations thereof.

Another possibility in bash, ksh or zsh is to use the typeset builtin to declare the variable as an integer. Then every assignment to it performs arithmetic evaluation.

typeset -i s t
t=20
s=t+30
echo "$s"
1

Here is one way:

t=20  

s=$((t+30))  # or s="$((t+30))"

echo "$s"
MikeD
  • 810
0

You can perform arithmetic using the expr command, take e.g.:

t=20
s=$(expr "$t" + 30)
echo "$s"

type man expr on your terminal for more info.