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 B=20 expr $A + $B # outputs 30 expr $A - $B # outputs -10 expr $A \* $B # outputs 200 (asterisk must be escaped) expr $A / $B # outputs 0 expr $A % $B # outputs 10

Results can be stored in a variable using command substitution: abc=$(expr $A + $B) echo $abc # 30

Command substitution also allows extracting data, such as an IP address: IPADDR=$(ifconfig eth0 | grep "inet" | awk '{print $2}') 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" echo $webserver # nginx 1.11 webserver='nginx 1.11' echo $webserver # nginx 1.11

Backticks (``) perform command substitution as well, useful for nesting commands, though nesting can become cumbersome: pwd which pwd rpm -qf $(which pwd) # coreutils-8.22-15.el7.x86_64 rpm -q `rpm -qf \\`which pwd\\`` # demonstrates nesting difficulty

shellArithmeticVariable 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

login 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.