Fundamentals 4 min read

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.

DevOps Cloud Academy
DevOps Cloud Academy
DevOps Cloud Academy
Using Numeric Operators and Variable Assignment in Shell Scripts

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 10

Results 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.216

Quoting 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.11

Backticks (``) 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 difficulty
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

ArithmeticVariable Assignmentcommand substitutionquoting
DevOps Cloud Academy
Written by

DevOps Cloud Academy

Exploring industry DevOps practices and technical expertise.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.