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.
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.
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"
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.
man bash
(or your preferred shell) and read the section on arithmetic. – Chris Davies Mar 11 '17 at 00:00