Unix Shell Script Arithmetic and Boolean Operators Examples

By Vijay

By Vijay

I'm Vijay, and I've been working on this blog for the past 20+ years! I’ve been in the IT industry for more than 20 years now. I completed my graduation in B.E. Computer Science from a reputed Pune university and then started my career in…

Learn about our editorial policies.
Updated March 9, 2024

Working with Shell Arithmetic and Boolean Operators in Unix:

In this tutorial, we will review the various operators that are supported by the Unix shell.

Operators are used for manipulating variables and constants in shell programs. They are required to perform mathematical operations. 

Unix Shell Script

Here, we will explain to you more about working with Arithmetic Operators.

Unix Video #14:

Note that the back-tick (`) is often used here – when executing a command, everything between the back-ticks is executed and substituted with the result before the remainder of the command is executed.

In newer shells (Example: bash), the same result can be achieved by embedding the expression between ‘$(’ and ‘)’.

Operators in Unix

#1) Shell Arithmetic Operators Example

These consist of basic mathematical operations:

  • Addition: +
  • Subtraction: –
  • Multiplication: *
  • Division: /
  • Modulus: %

Each of these operators performs the operation on two integer variables or constants.

For Example, the below program illustrates each of these operations:

$ c=`expr $a + $b`
$ echo “the value of addition=$c”
$ d=`expr $a - $b`
$ echo “the value of subtraction=$d”
$ e= expr $a \* $b`
$ echo “the value of multiplication=$e”
$ f=`expr $a / $b`
$ echo “the value of division=$f”
$ g= echo `expr $a % $b`
$ echo “the value of modulus=$c”

The Unix shell does not natively support floating point operations.  A separate command-line tool must be used for this.  The ‘bc’ co0mmand is the most standard tool for this.

Example:

$ c = `echo “$a + $b” | bc`
$ d = `echo “$a + $b” | bc`

Note that each of the operators needs to be surrounded by a space on both sides, and the ‘*’ operators need to be escaped with a backslash ‘\’.

#2) Shell Logical Boolean Operators Example

The logical operators in Unix are as follows:

  • Not:!
  • And: -a
  • Or: -o

These operators and their usage will be covered in detail in the next tutorial.

PREV Tutorial | NEXT Tutorial

Was this helpful?

Thanks for your feedback!

Leave a Comment