Advance Shell Scripting Concepts
Section 5: Advanced Shell Scripting Concepts
Lesson 1: Handling Signals and Traps
Handling signals and traps in shell scripts allows for graceful response to events such as interruptions and errors.
1.1 Responding to Signals
#!/bin/bash
# Handling signals in shell scripts
# Define a function to handle the interrupt signal (Ctrl+C)
handle_interrupt() {
echo "Script interrupted. Cleaning up..."
# Additional cleanup tasks
exit 1
}
# Register the function to handle the interrupt signal
trap 'handle_interrupt' INT
# Main script logic
echo "Running script. Press Ctrl+C to interrupt."
while true; do
# Main script tasks
sleep 1
done
1.2 Using Traps for Signal Handling
#!/bin/bash
# Using traps for signal handling
# Define a function to handle the exit signal
handle_exit() {
echo "Script is exiting. Performing cleanup..."
# Additional cleanup tasks
}
# Register the function to handle the exit signal
trap 'handle_exit' EXIT
# Main script logic
echo "Running script. This will perform cleanup on exit."
# Main script tasks
sleep 3
Lesson 2: Regular Expressions in Shell Scripts
Regular expressions (regex) are powerful tools for pattern matching and text manipulation in shell scripts.
2.1 Pattern Matching with grep
#!/bin/bash
# Pattern matching with grep
# Search for lines containing "error" in a file
grep "error" logfile.txt
# Search for lines starting with "warning"
grep "^warning" logfile.txt
2.2 Text Manipulation Using sed
#!/bin/bash
# Text manipulation using sed
# Replace "apple" with "orange" in a file
sed -i 's/apple/orange/g' fruits.txt
# Delete lines containing "banana"
sed -i '/banana/d' fruits.txt
Understanding how to handle signals gracefully and utilize regular expressions for text manipulation enhances the capabilities of shell scripts. In the next sections, we'll explore more advanced scripting techniques and real-world applications.