What is Bash?
- A shell → provides a command-line interface (CLI).
- A 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:
- The terminal captures your input.
- The shell (Bash) interprets it.
- The kernel executes the command.
- Output is displayed back in the terminal.
Example:
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):
#!/bin/bash
echo "Hello, Linux World!"
Run it:
bash hello.sh
or (if executable):
./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
=):
name="Amr"
age=30
- Access a variable using
$:
echo "My name is $name and I am $age years old."
- Variables are by default strings, unless used in arithmetic:
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:
printenv
or
env
- Show a specific variable:
echo $PATH
Creating Environment Variables
- Make a variable global (export it):
export PROJECT_DIR=/home/amr/projects
- Now any program launched from this shell can access it.
- To make it permanent, add it to
~/.bashrcor~/.bash_profile.
Example Workflow
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.
#!/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.
#!/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.
#!/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.
#!/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.
- Create a new file:
nano hello.sh
- Add this content:
#!/bin/bash
# A simple script that greets the user
echo "Hello, $USER! Today is $(date)."
- Save and exit (
CTRL+O,CTRL+X).
- Make the script executable:
chmod +x hello.sh
- Run the script:
./hello.sh
Example: Automating a Backup
#!/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
Documentsfolder. - 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:
crontab -e
- Example: Run the backup script every day at 2 AM:
0 2 * * * /home/amr/backup.sh
- Cron format =
minute hour day month weekday command.