System Scripting Lab 03

Processes, Arithmetic Operators and Control Flow

Setup

mkdir lab03
cd lab03

Exercise 1: Process Monitoring

Start gedit

gedit

List all running processes

ps -ef

Find gedit process

ps -ef | grep gedit

Kill the process

kill PID

Explanation:

Exercise 2: Root Processes Script

#!/bin/bash

# Output all processes owned by root into file
ps -U root -u root u > root_processes.txt

# Display file contents
echo "All root processes:"
cat root_processes.txt

# Filter lines ending with ]
echo "Processes ending with ]:"
grep "]$" root_processes.txt

Explanation:

Exercise 3: Arithmetic Script

#!/bin/bash

# Prompt user for input
read -p "Enter first number: " num1
read -p "Enter second number: " num2

# Compare numbers
if [ $num1 -gt $num2 ]; then
    # Perform division
    result=$((num1 / num2))
    echo "Division result: $result"
else
    # Perform multiplication
    result=$((num1 * num2))
    echo "Multiplication result: $result"
fi

Explanation:

Exercise 4: File Checking Script

#!/bin/bash

# Check if argument provided
if [ $# -eq 0 ]; then
    echo "Usage: $0 filename"
    exit 1
fi

file=$1

# Check if file exists
if [ -f "$file" ]; then
    echo "File exists"

    # Check if file is empty
    if [ ! -s "$file" ]; then
        echo "File is empty. Writing environment variables."
        env > "$file"
    else
        echo "File is not empty"
    fi

else
    echo "File does not exist. Creating file."
    touch "$file"

    # Write environment variables
    env > "$file"
    echo "Environment variables written to file"
fi

Explanation:

Exercise 5: Menu-Driven Arithmetic Script

#!/bin/bash

while true
do
    echo "====== MENU ======"
    echo "1. Addition"
    echo "2. Subtraction"
    echo "3. Multiplication"
    echo "4. Division"
    echo "5. Exit"

    # User choice
    read -p "Enter choice: " choice

    # Exit condition
    if [ "$choice" -eq 5 ]; then
        echo "Goodbye!"
        break
    fi

    # Get numbers
    read -p "Enter first number: " num1
    read -p "Enter second number: " num2

    case $choice in
        1)
            echo "Result: $((num1 + num2))"
            ;;
        2)
            echo "Result: $((num1 - num2))"
            ;;
        3)
            echo "Result: $((num1 * num2))"
            ;;
        4)
            if [ $num2 -ne 0 ]; then
                echo "Result: $((num1 / num2))"
            else
                echo "Error: Division by zero"
            fi
            ;;
        *)
            echo "Invalid choice!"
            ;;
    esac
done

Explanation:

Key Exam Tips