Welcome to the world of Bash scripting! This powerful tool automates tasks, manages systems, and unlocks the full potential of your Linux/macOS terminal. Let’s break down core concepts with practical examples:
1. The Shebang Line
Always start scripts with this “magic line” to specify the interpreter:
#!/bin/bash
2. Variables
Declare variables and access them with $
:
name="Alice"
echo "Hello, $name!" # Output: Hello, Alice!
3. User Input
Use read
for interactive scripts:
echo "What's your age?"
read age
echo "You're $age years old."
4. Conditionals (if
Statements)
Compare values with -eq
(equal), -lt
(less than), etc.:
count=10
if [ $count -eq 10 ]; then
echo "Count is 10"
elif [ $count -lt 5 ]; then
echo "Too low"
else
echo "Invalid"
fi
File Checks:
if [ -f "myfile.txt" ]; then
echo "File exists"
fi
5. Loops
a) for
Loop:
for fruit in apple banana cherry; do
echo "I like $fruit"
done
b) while
Loop:
counter=1
while [ $counter -le 3 ]; do
echo "Count: $counter"
((counter++))
done
6. Command Arguments
Access arguments with $1
, $2
, etc.:
#!/bin/bash
echo "First argument: $1"
echo "All arguments: $@"
Run with: ./script.sh arg1 arg2
7. Exit Codes
Check success/failure of previous command with $?
:
grep "search" file.txt
if [ $? -eq 0 ]; then
echo "Text found!"
else
echo "Text not found."
fi
8. Functions
Reusable code blocks with parameters:
greet() {
echo "Hello, $1!"
}
greet "Bob" # Output: Hello, Bob!
Practical Example: Backup Script
#!/bin/bash
# Backup directory creator
backup_dir="/tmp/backup_$(date +%Y%m%d)"
mkdir -p $backup_dir
# Copy files
cp -r ~/documents $backup_dir && \
echo "Backup completed in $backup_dir"
Running Your Script
- Make it executable:
chmod +x script.sh
- Execute:
./script.sh
Key Tips:
- Case Sensitivity:
VAR
≠var
- Spacing: Use spaces in
[ conditions ]
- Debugging: Add
set -x
at the start to trace execution - Extensions: Use
.sh
(e.g.,myscript.sh
) for clarity
Master these fundamentals to automate file management, system monitoring, and complex workflows. Bash turns repetitive tasks into one-click solutions! Practice by modifying examples and explore advanced topics like arrays (${my_array[@]}
) and regular expressions next. Happy scripting! 🐚