Using Numeric Operators and Variable Assignment in Shell Scripts
This article explains how to perform arithmetic with the expr command, assign results to variables, extract information using command substitution, and correctly apply quoting and backticks in Bash to handle spaces, special characters, and nested commands.
The expr command provides basic arithmetic in shell scripts; its syntax is expr variable1 operator variable2 and requires spaces around the operator.
Examples:
A=10<br/>B=20<br/>expr $A + $B # outputs 30<br/>expr $A - $B # outputs -10<br/>expr $A \* $B # outputs 200 (asterisk must be escaped)<br/>expr $A / $B # outputs 0<br/>expr $A % $B # outputs 10Results can be stored in a variable using command substitution: abc=$(expr $A + $B)<br/>echo $abc # 30 Command substitution also allows extracting data, such as an IP address:
IPADDR=$(ifconfig eth0 | grep "inet" | awk '{print $2}')<br/>echo $IPADDR # e.g., 10.141.113.216Quoting rules are demonstrated: double quotes preserve spaces and allow variable expansion, while single quotes treat everything literally and require escaping for embedded single quotes.
webserver="nginx 1.11"<br/>echo $webserver # nginx 1.11<br/>webserver='nginx 1.11'<br/>echo $webserver # nginx 1.11Backticks (``) perform command substitution as well, useful for nesting commands, though nesting can become cumbersome:
pwd<br/>which pwd<br/>rpm -qf $(which pwd) # coreutils-8.22-15.el7.x86_64<br/>rpm -q `rpm -qf \\`which pwd\\`` # demonstrates nesting difficultySigned-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
DevOps Cloud Academy
Exploring industry DevOps practices and technical expertise.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
