Unix - Shell Scripting with Conditional Statements and Loops

Shell scripting is one of the most powerful features of UNIX. A shell script is a text file containing a sequence of commands that are executed by the shell. Instead of typing commands manually every time, users can automate repetitive tasks by writing them into a script.

Conditional statements and loops are fundamental programming constructs in shell scripting. They allow scripts to make decisions and perform repetitive tasks efficiently. Together, they enable the creation of intelligent and dynamic automation solutions.

What is a Shell Script?

A shell script is a file that contains UNIX commands and programming instructions. The shell reads the file and executes the commands one by one.

A simple shell script example:

#!/bin/sh
echo "Welcome to UNIX Shell Scripting"

The first line, known as the shebang (#!), tells the system which interpreter should execute the script.

After saving the file, it can be made executable using:

chmod +x script.sh

Run the script using:

./script.sh

Importance of Conditional Statements

Conditional statements allow a script to make decisions based on specific conditions.

For example:

  • Checking if a file exists

  • Verifying user input

  • Determining system status

  • Performing different actions based on conditions

Without conditional statements, scripts would execute the same commands every time regardless of circumstances.

The if Statement

The if statement evaluates a condition and executes commands when the condition is true.

Syntax

if [ condition ]
then
    commands
fi

Example

#!/bin/sh

num=10

if [ $num -gt 5 ]
then
    echo "Number is greater than 5"
fi

Output:

Number is greater than 5

The condition checks whether the value of num is greater than 5.

The if-else Statement

The if-else statement provides an alternative action when the condition is false.

Syntax

if [ condition ]
then
    commands
else
    commands
fi

Example

#!/bin/sh

age=16

if [ $age -ge 18 ]
then
    echo "Eligible to vote"
else
    echo "Not eligible to vote"
fi

Output:

Not eligible to vote

The if-elif-else Statement

When multiple conditions need to be checked, elif is used.

Syntax

if [ condition1 ]
then
    commands
elif [ condition2 ]
then
    commands
else
    commands
fi

Example

#!/bin/sh

marks=75

if [ $marks -ge 90 ]
then
    echo "Grade A"
elif [ $marks -ge 70 ]
then
    echo "Grade B"
else
    echo "Grade C"
fi

Output:

Grade B"

Common Comparison Operators

Numeric Operators

Operator Meaning
-eq Equal to
-ne Not equal to
-gt Greater than
-lt Less than
-ge Greater than or equal to
-le Less than or equal to

Example:

if [ $a -eq $b ]
then
    echo "Values are equal"
fi

String Operators

Operator Meaning
= Equal
!= Not equal
-z String length is zero
-n String length is not zero

Example:

name="Unix"

if [ "$name" = "Unix" ]
then
    echo "Match found"
fi

File Test Operators

UNIX shell scripting can check file properties.

Operator Description
-f File exists
-d Directory exists
-r Read permission
-w Write permission
-x Execute permission

Example:

if [ -f data.txt ]
then
    echo "File exists"
fi

The case Statement

The case statement is used when multiple choices are possible.

Syntax

case variable in
pattern1)
    commands
    ;;
pattern2)
    commands
    ;;
*)
    commands
    ;;
esac

Example

#!/bin/sh

echo "Enter a choice:"
read choice

case $choice in
1)
    echo "Option One Selected"
    ;;
2)
    echo "Option Two Selected"
    ;;
*)
    echo "Invalid Choice"
    ;;
esac

Introduction to Loops

Loops repeatedly execute a set of commands until a condition is met.

Loops help in:

  • Processing large amounts of data

  • Automating repetitive tasks

  • Generating reports

  • Managing files and directories

UNIX provides several types of loops.

The for Loop

The for loop iterates through a list of values.

Syntax

for variable in list
do
    commands
done

Example

#!/bin/sh

for i in 1 2 3 4 5
do
    echo $i
done

Output:

1
2
3
4
5

Loop Through Files

for file in *.txt
do
    echo $file
done

This displays all text files in the current directory.

The while Loop

The while loop continues execution as long as the condition remains true.

Syntax

while [ condition ]
do
    commands
done

Example

#!/bin/sh

count=1

while [ $count -le 5 ]
do
    echo $count
    count=`expr $count + 1`
done

Output:

1
2
3
4
5

The until Loop

The until loop executes until a condition becomes true.

Syntax

until [ condition ]
do
    commands
done

Example

#!/bin/sh

count=1

until [ $count -gt 5 ]
do
    echo $count
    count=`expr $count + 1`
done

Output:

1
2
3
4
5

Loop Control Statements

break Statement

The break statement immediately terminates a loop.

Example:

for i in 1 2 3 4 5
do
    if [ $i -eq 3 ]
    then
        break
    fi
    echo $i
done

Output:

1
2

continue Statement

The continue statement skips the current iteration and moves to the next one.

Example:

for i in 1 2 3 4 5
do
    if [ $i -eq 3 ]
    then
        continue
    fi
    echo $i
done

Output:

1
2
4
5

Combining Conditions and Loops

Conditional statements are often used inside loops.

Example:

for num in 1 2 3 4 5 6
do
    if [ $num -eq 4 ]
    then
        echo "Found number 4"
    fi
done

Output:

Found number 4

This combination allows scripts to perform complex decision-making during repetitive operations.

Practical Applications

User Account Monitoring

for user in `who | awk '{print $1}'`
do
    echo $user
done

File Backup Automation

if [ -d backup ]
then
    cp *.txt backup/
fi

Log File Analysis

while read line
do
    echo $line
done < logfile.txt

Batch File Processing

for file in *.log
do
    mv $file archive/
done

Advantages of Using Conditional Statements and Loops

  1. Automate repetitive administrative tasks.

  2. Reduce manual effort and human errors.

  3. Improve script flexibility and intelligence.

  4. Enable dynamic decision-making.

  5. Simplify system management.

  6. Increase productivity and efficiency.

  7. Support large-scale file and process management.

Conclusion

Conditional statements and loops form the foundation of UNIX shell scripting. Conditional statements such as if, if-else, if-elif, and case allow scripts to make decisions based on specific conditions, while loops such as for, while, and until enable repeated execution of commands. Together, they provide the ability to create powerful automation scripts for system administration, file management, process monitoring, backups, reporting, and numerous other UNIX tasks. Mastering these constructs is essential for developing efficient and professional shell scripts in UNIX environments.