Bash scripting is one of the most fundamental and practical skills in the world of Linux. By learning Bash, you can automate repetitive tasks, execute multiple commands in sequence, and build small but powerful tools for system management. This article is designed for people with no programming background who want to start from scratch.
ls, cd, and mkdir. If you've never used the terminal before, don't worry – you can start right now.
1. What is the Shell and Why Bash?
The shell in Linux is a program that takes your keyboard input and passes it to the operating system kernel for execution. When you type something in the terminal, you're actually communicating with the shell. Bash is the most popular shell and is the default on most Linux distributions. The name Bash stands for Bourne Again SHell, which has been used on Unix and Linux systems since 1989.
To write a script, simply create a new text file with a .sh extension, write your commands inside, and then give the file execution permission. The first line of every script must specify the interpreter. This line is called the Shebang:
#!/bin/bash
This line tells the system to use Bash to execute the commands. The rest of the lines are the same commands you'd type in the terminal.
2. Variables – Storing Information
In Bash, you can store information in variables. Variables are places to hold values. To define a variable, simply write its name, add an = sign, and specify the value. Important: There should be no spaces between the variable name, the equals sign, and the value.
#!/bin/bash
name="Sara"
age=25
echo "Hello, my name is $name and I am $age years old."
When you want to read a variable's value, add a $ before it. For example, $name returns the value of the name variable.
echo "$name" is better than echo $name.
Special and Predefined Variables
Bash has several special variables that make scripting easier. Here are some important ones:
| Variable | Description |
|---|---|
$0 | Name of the script itself |
$1, $2, ... | Input arguments to the script |
$# | Number of arguments |
$@ | List of all arguments |
$? | Exit code of the last command (0 means success) |
$$ | Process ID (PID) of the script |
3. Getting User Input
Sometimes you want to get information from the user running the script. This is done with the read command:
#!/bin/bash
echo "Please enter your name:"
read user_name
echo "Hello $user_name! Welcome."
You can also use the -p option to display the prompt directly:
read -p "Enter your city: " city
echo "Your city: $city"
Capturing Command Output
You can store the output of a command in a variable using backticks or $():
current_date=$(date)
echo "Today's date: $current_date"
4. Decision Making with Conditionals (if)
In scripting, you can perform different actions based on conditions. The if structure allows you to do this:
#!/bin/bash
read -p "Enter a number: " num
if [ $num -gt 10 ]; then
echo "The number is greater than 10."
elif [ $num -eq 10 ]; then
echo "The number is equal to 10."
else
echo "The number is less than 10."
fi
This example uses comparison operators. Here are the most common ones:
| Operator | Meaning |
|---|---|
-eq | Equal |
-ne | Not equal |
-gt | Greater than |
-lt | Less than |
-ge | Greater than or equal |
-le | Less than or equal |
= (inside [[ ]]) | String equality |
!= (inside [[ ]]) | String inequality |
-z | String is empty |
-n | String is not empty |
[ $num -gt 10 ] is correct, but [$num -gt 10] is wrong.
5. Loops for Repetition
When you need to repeat a task multiple times, loops come to your aid.
for Loop
This loop is used to iterate over a list or range:
#!/bin/bash
for i in 1 2 3 4 5; do
echo "Number $i"
done
# Iterating over text files
for file in *.txt; do
echo "Processing file: $file"
done
while Loop
Runs as long as the condition is true:
#!/bin/bash
counter=1
while [ $counter -le 5 ]; do
echo "Counter: $counter"
((counter++)) # Increment counter
done
until Loop
Works opposite to while – runs until the condition becomes true:
#!/bin/bash
counter=1
until [ $counter -gt 5 ]; do
echo "Counter: $counter"
((counter++))
done
6. Functions – Organizing Code
If you find yourself repeating a block of code, it's better to put it inside a function. This makes your code cleaner and reusable.
#!/bin/bash
greet() {
echo "Hello $1! Welcome."
}
greet "Ahmad"
greet "Maryam"
Here, $1 is the first argument passed to the function. Functions can return an exit code with return or produce output with echo.
7. Arrays – Lists of Data
An array is a variable that holds multiple values. In Bash, arrays are indexed starting from zero.
#!/bin/bash
fruits=("Apple" "Banana" "Orange")
echo "First fruit: ${fruits[0]}"
echo "All fruits: ${fruits[@]}"
# Adding an element to the end
fruits+=("Grape")
echo "Number of elements: ${#fruits[@]}"
${#fruits[@]} gives you the number of elements in the array.
8. Error Handling and Debugging
When your script fails, you need to know how to find the issue. Here are some simple tools:
$?: Shows the exit code of the last command. If it's 0, the command executed successfully.set -e: Stops script execution immediately when an error occurs.set -x: Displays each command before executing it (useful for debugging).
#!/bin/bash
set -e # Stop on error
mkdir /root/test # This command will fail (permission denied)
echo "This line will not be executed."
9. Text Processing with Helper Tools
Bash is powerful on its own, but when combined with tools like grep, sed, and awk, it becomes a text processing powerhouse. For example, you can search a log file and extract specific lines:
#!/bin/bash
# Find lines containing "error"
grep "error" /var/log/syslog
You can also use regular expressions for more complex patterns.
10. Practical Examples to Practice
Example 1: Simple Backup
#!/bin/bash
backup_dir="/tmp/backup_$(date +%Y%m%d)"
mkdir -p "$backup_dir"
cp -r /home/user/documents "$backup_dir"
echo "Backup saved to $backup_dir"
Example 2: Disk Usage Alert
#!/bin/bash
usage=$(df -h / | awk 'NR==2 {print $5}' | sed 's/%//')
if [ $usage -gt 80 ]; then
echo "Warning: Disk usage is over 80%."
# You could send an email or SMS here
fi
Example 3: Counting Files of a Specific Type
#!/bin/bash
count=$(ls -1 *.log 2>/dev/null | wc -l)
echo "Number of log files: $count"
Conclusion and Next Steps
In this article, you learned the fundamentals of Bash scripting. Now you can write small scripts and gradually make them more complex. To keep improving:
- Write a simple script every day (backup, monitoring, or file organization).
- Browse the official Bash documentation: GNU Bash Manual
- Read the book «The Linux Command Line» (available at Linux Library).
- Get help from online communities like Stack Overflow.