Master Bash Scripting with Real-World Examples
What is Bash Scripting?
Bash scripting is a powerful way to automate tasks on Unix-like operating systems. Bash (Bourne Again SHell) is the default shell for many Linux distributions and macOS. A Bash script is a plain text file containing a series of commands that the shell executes in sequence.
Whether you're a system administrator, developer, or Linux enthusiast, learning Bash scripting enables you to save time, reduce human error, and increase productivity.
Creating Your First Bash Script
To create a Bash script, follow these steps:
- Create a new file with a
.sh
extension. - Add the shebang line at the top:
#!/bin/bash
- Write your Bash commands below.
- Make the script executable using
chmod +x script.sh
- Run it with
./script.sh
#!/bin/bash
echo "Hello, world!"
Variables and User Input
Bash supports variables, both predefined and user-defined. Variables don’t require a data type and are assigned with =
without spaces.
#!/bin/bash
name="Myname"
echo "Hello, $name!"
Reading user input:
#!/bin/bash
echo "Enter your name:"
read username
echo "Welcome, $username!"
Conditionals in Bash
Conditional statements allow your scripts to make decisions. Bash supports if
, elif
, and else
.
#!/bin/bash
num=10
if [ $num -gt 5 ]; then
echo "Greater than 5"
elif [ $num -eq 5 ]; then
echo "Equal to 5"
else
echo "Less than 5"
fi
Loops: Automate Repetition
Loops let you perform tasks multiple times. Bash has for
, while
, and until
loops.
#!/bin/bash
for i in 1 2 3 4 5
do
echo "Looping ... number $i"
done
#!/bin/bash
count=1
while [ $count -le 5 ]
do
echo "Count: $count"
((count++))
done
Functions in Bash
Functions allow code reuse and organization. Define them before calling.
#!/bin/bash
greet() {
echo "Hello, $1!"
}
greet "Sublimity Dev Blog"
Practical Examples
Real-world uses of Bash scripts include automation, backups, and system monitoring.
1. Backup Files
#!/bin/bash
tar -czf backup_$(date +%F).tar.gz /home/username/documents
2. Monitor Disk Space
#!/bin/bash
df -h | grep "/dev/sd"
3. User Account Report
#!/bin/bash
cut -d: -f1 /etc/passwd
Debugging and Best Practices
- Use
set -x
to debug. - Quote your variables:
"$var"
- Always check for command success using
$?
- Add comments for maintainability.
#!/bin/bash
set -x # Start debugging mode
ls /nonexistentdir
set +x # Stop debugging mode