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.
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.Sign up to join this community
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
t=20 let s=t+30 echo "$s"
((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"
Here is one way:
t=20 s=$((t+30)) # or s="$((t+30))" echo "$s"
You can perform arithmetic using the
expr command, take e.g.:
t=20 s=$(expr "$t" + 30) echo "$s"
man expr on your terminal for more info.