OS: Linux Shell Scripting

Bash (Bourne Again SHell) is the most widely used shell in Linux systems. It acts as a command interpreter, letting you run commands, automate tasks, and write scripts.

What is Bash?

  • shell → provides a command-line interface (CLI).
  • scripting language → lets you automate repetitive tasks with scripts.
  • Default shell in most Linux distributions.
  • Successor to the original Bourne Shell (sh).

Bash as a Command Interpreter

When you type a command into the terminal:

  1. The terminal captures your input.
  2. The shell (Bash) interprets it.
  3. The kernel executes the command.
  4. Output is displayed back in the terminal.

Example:

bash
ls -l /home

Here, ls is the command, -l is an option, and /home is an argument.


Bash Scripts

Bash is not just interactive — you can write scripts.

  • A script is a text file with commands executed in order.
  • Convention: script files end with .sh.

Example script (hello.sh):

bash
#!/bin/bash
echo "Hello, Linux World!"

Run it:

bash
bash hello.sh

or (if executable):

bash
./hello.sh


Variables and Environment Variables

In Bash, variables let you store and reuse values. They can be local to your script/session or global (environment variables) that affect the entire shell and programs.


Defining Variables

  • Assign a value (no spaces around =):
  • bash
    name="Amr"
    age=30

  • Access a variable using $:
  • bash
    echo "My name is $name and I am $age years old."

  • Variables are by default strings, unless used in arithmetic:
  • bash
    num1=5
    num2=3
    echo $((num1 + num2))   # outputs 8


Environment Variables

Environment variables are special variables that affect how the system and programs behave.

  • Common examples:
  • $HOME → your home directory.
  • $USER → your username.
  • $PATH → directories where the shell looks for commands.
  • $SHELL → the current shell program.
  • Display all environment variables:
  • bash
    printenv

or

bash
env

  • Show a specific variable:
  • bash
    echo $PATH


Creating Environment Variables

  • Make a variable global (export it):
  • bash
    export PROJECT_DIR=/home/amr/projects

  • Now any program launched from this shell can access it.
  • To make it permanent, add it to ~/.bashrc or ~/.bash_profile.

Example Workflow

bash
name="LinuxUser"
export PATH=$PATH:/home/$USER/scripts
echo "Hello, $name!"
echo "New PATH is: $PATH"

This sets a local variable (name), then modifies the global PATH so the system also looks in /home/LinuxUser/scripts for executables.


Control Structures in Bash (if, for, while, case)

Control structures let you make decisions and repeat actions in scripts, just like in programming languages.


 `if` – Conditional Execution

Used to run commands only if a condition is true.

bash
#!/bin/bash

echo "Enter a number:"
read num

if [ $num -gt 10 ]; then
    echo "Number is greater than 10"
elif [ $num -eq 10 ]; then
    echo "Number is exactly 10"
else
    echo "Number is less than 10"
fi


 `for` – Loop Through Items

Iterates over a list of items.

bash
#!/bin/bash

for file in *.txt; do
    echo "Processing $file"
done

  • Useful for batch operations (e.g., renaming, compressing files).

 `while` – Loop While Condition is True

Repeats as long as the condition holds true.

bash
#!/bin/bash

count=1
while [ $count -le 5 ]; do
    echo "Count is $count"
    count=$((count + 1))
done


 `case` – Multi-Option Branching

Simplifies checking against multiple values.

bash
#!/bin/bash

echo "Choose an option: start / stop / restart"
read action

case $action in
    start)
        echo "Starting service..."
        ;;
    stop)
        echo "Stopping service..."
        ;;
    restart)
        echo "Restarting service..."
        ;;
    *)
        echo "Invalid option"
        ;;
esac


Simple Scripts and Automation

One of the biggest strengths of Linux is the ability to automate tasks with Bash scripts. Instead of repeating commands, you can write them once in a script and run them whenever needed.

Writing a Simple Script

A Bash script is just a text file containing commands, executed line by line.

  1. Create a new file:
  2. bash
    nano hello.sh

  1. Add this content:
  2. bash
    #!/bin/bash
    # A simple script that greets the user
    echo "Hello, $USER! Today is $(date)."

  1. Save and exit (CTRL+OCTRL+X).
  1. Make the script executable:
  2. bash
    chmod +x hello.sh

  1. Run the script:
  2. bash
    ./hello.sh


Example: Automating a Backup

bash
#!/bin/bash
# Backup Documents folder into a tar.gz archive

BACKUP_FILE="backup-$(date +%F).tar.gz"
tar -czf $BACKUP_FILE ~/Documents
echo "Backup saved as $BACKUP_FILE"

  • Compresses the Documents folder.
  • Names the backup with today’s date.
  • Useful for daily/weekly automation.

Scheduling Scripts with Cron

Linux has cron, a scheduler that automates scripts at specific times.

  • Edit your cron jobs:
  • bash
    crontab -e

  • Example: Run the backup script every day at 2 AM:
  • bash
    0 2 * * * /home/amr/backup.sh

  • Cron format = minute hour day month weekday command.