Advanced Scripting Techniques
Error Handling and Debugging Strategies
Advanced shell scripting requires robust error management and sophisticated debugging techniques to create reliable and efficient scripts.
Error Handling Mechanisms
#!/bin/bash
## Trap error handling
set -e ## Exit on first error
set -u ## Exit on undefined variables
set -o pipefail ## Capture pipeline errors
error_handler() {
echo "Error occurred in script execution"
exit 1
}
trap error_handler ERR
Debugging Techniques
Debugging Option |
Description |
Command |
Verbose Mode |
Print commands before execution |
bash -v script.sh |
Trace Mode |
Display detailed execution trace |
bash -x script.sh |
Syntax Check |
Validate script syntax |
bash -n script.sh |
Advanced Function Implementation
#!/bin/bash
## Function with multiple return values
get_system_info() {
local hostname=$(hostname)
local kernel_version=$(uname -r)
local cpu_cores=$(nproc)
## Return array-like output
echo "$hostname $kernel_version $cpu_cores"
}
## Capture function output
read -r host kernel cores <<< $(get_system_info)
Script Optimization Workflow
graph TD
A[Script Analysis] --> B[Performance Profiling]
B --> C[Identify Bottlenecks]
C --> D[Optimize Code]
D --> E[Validate Performance]
E --> F[Implement Improvements]
Parallel Processing Techniques
#!/bin/bash
## Parallel command execution
process_files() {
local files=("$@")
for file in "${files[@]}"; do
process_single_file "$file" &
done
wait
}
## Background job management
process_files file1.txt file2.txt file3.txt
#!/bin/bash
validate_input() {
local input="$1"
[[ "$input" =~ ^[0-9]+$ ]] || {
echo "Invalid numeric input"
return 1
}
}
## Usage example
validate_input "123" || exit 1