Operator Usage

Tutorial 3 of 4

Introduction

In this tutorial, we aim to guide you through the correct usage of logical operators in shell scripting. By the end of this tutorial, you will have a clear understanding of how to combine conditional statements using logical operators to evaluate more complex conditions in your shell scripts.

Prerequisites:

  • Basic understanding of shell scripting
  • A Unix/Linux system to practice

Step-by-Step Guide

Logical operators are special symbols that control the execution of conditional expressions and loops. In shell scripting, there are three types of logical operators: AND, OR, and NOT.

  • AND Operator: If both operands are true, then the condition becomes true. This is denoted as -a or &&.
  • OR Operator: If any of the two operands are true, then the condition becomes true. This is denoted as -o or ||.
  • NOT Operator: This is used to reverse the logical state of its operand. If a condition is true, then the Logical NOT operator will make it false. This is denoted as !.

Best practices:
- Always use spaces around operators to avoid syntax errors.
- Use brackets to clarify precedence when multiple operators are used together.

Code Examples

Example 1: AND Operator

age=25

if [ $age -gt 18 ] && [ $age -lt 30 ]
then
    echo "Valid age"
else
    echo "Invalid age"
fi

This script checks if the variable age is greater than 18 AND less than 30. If both conditions are true, it prints "Valid age"; otherwise, "Invalid age".

Example 2: OR Operator

is_day=true
is_sunny=false

if [ $is_day = true ] || [ $is_sunny = true ]
then
    echo "Go outside"
else
    echo "Stay indoors"
fi

This script checks if it is day OR if it is sunny. If either condition is true, it advises to "Go outside"; otherwise, "Stay indoors".

Summary

In this tutorial, we've covered how to use AND, OR, and NOT logical operators in shell scripting. Next, you can learn about arithmetic operators and how to use them in shell scripts. Visit Shell Scripting Tutorial for further learning.

Practice Exercises

  1. Write a shell script that checks if a number is positive OR even.
  2. Write a shell script that checks if a person is eligible to vote AND to drive (assume the legal age for both is 18).

Solutions:

num=10

if [ $num -gt 0 ] || [ $(($num % 2)) -eq 0 ]
then
    echo "Number is positive or even"
else
    echo "Number is not positive or even"
fi
age=20

if [ $age -ge 18 ]
then
    echo "Person is eligible to vote and drive"
else
    echo "Person is not eligible to vote or drive"
fi

Keep practicing with different conditions and operators to get a good grip on logical operators!