Advanced Bash Scripting
Chapter 48: Advanced Bash Scripting
Section titled “Chapter 48: Advanced Bash Scripting”Overview
Section titled “Overview”This chapter covers advanced bash scripting techniques for automation.
48.1 Process Management
Section titled “48.1 Process Management”Background Processes
Section titled “Background Processes”# Run in backgroundcommand &./script.sh &
# Wait for background processwait $PID
# Jobs controljobsfg %1bg %1Ctrl+Z # SuspendSignals
Section titled “Signals”# Trap signalstrap 'echo "Caught SIGINT"' INTtrap 'cleanup' EXIT
# Common signals# SIGINT (2) - Ctrl+C# SIGTERM (15) - Graceful termination# SIGKILL (9) - Force kill# SIGHUP (1) - Hangup48.2 Process Substitution
Section titled “48.2 Process Substitution”Examples
Section titled “Examples”# Compare filesdiff <(sort file1) <(sort file2)
# While with process substitutionwhile read line; do process $linedone < <(command)
# Read from multiple filespaste <(cut -f1 file1) <(cut -f2 file2)48.3 Advanced Arrays
Section titled “48.3 Advanced Arrays”Associative Arrays
Section titled “Associative Arrays”# Requires bash 4+declare -A usersusers[admin]=rootusers[nginx]=www-data
# List keys/valuesecho ${!users[@]}echo ${users[@]}Array Operations
Section titled “Array Operations”# Slicing${array[@]:start:length}
# Search and replace in array${array[@]/old/new}
# Conditional filter${array[@]/*pattern*/}48.4 Advanced Functions
Section titled “48.4 Advanced Functions”Returning Values
Section titled “Returning Values”# Return statuscheck_service() { systemctl is-active $1 return $?}
# Return data via stdoutget_users() { awk -F: '$3 >= 1000 {print $1}' /etc/passwd}users=$(get_users)
# Using global variableRESULT=""store_result() { RESULT="computed value"}48.5 Error Handling
Section titled “48.5 Error Handling”Exit Codes
Section titled “Exit Codes”# Exit with statusexit 0 # Successexit 1 # Errorexit 2 # Misuseexit 126 # Not executableexit 127 # Command not found
# Check exit statuscommandif [ $? -eq 0 ]; then echo "Success"fi
# Set -e (exit on error)set -ecommand || { echo "Failed"; exit 1; }Debugging
Section titled “Debugging”# Verbose modeset -v
# Debug modeset -x
# Track errorsset -o errtraceset -o pipefail
# Combinedset -euo pipefail48.6 Parallel Processing
Section titled “48.6 Parallel Processing”# Parallel executionls *.log | xargs -P 4 -I {} gzip {}
# With GNU parallelcat hosts | parallel -j 4 ssh {} 'uptime'Background Jobs
Section titled “Background Jobs”# Run in parallelfor server in server1 server2 server3; do ssh $server 'apt update' &donewait
# Limit parallel jobssem -j 4 ./process.sh48.7 Text Processing
Section titled “48.7 Text Processing”# Print specific columnsawk '{print $1, $3}' file
# Field separatorawk -F: '{print $1}' /etc/passwd
# Conditionalawk '$3 > 1000 {print $1}' /etc/passwd
# Operationsawk '{sum+=$1} END {print sum}' file# Replacesed 's/old/new/g' filesed -i 's/old/new/g' file
# Delete linessed '/pattern/d' file
# Print linessed -n '1,10p' filesed -n '/start/,/end/p' file48.8 Secure Scripts
Section titled “48.8 Secure Scripts”Security Best Practices
Section titled “Security Best Practices”# Avoid eval# Sanitize input# Use quotes for variables# Don't use backticks (use $())# Check file permissions# Validate argumentsWhy This Matters in DevOps/SRE
Section titled “Why This Matters in DevOps/SRE”Advanced bash enables complex automation:
Advanced Bash in DevOps/SRE+------------------------------------------------------------------+| || Parallel Processing: || +----------------------------------------------------------+ || | xargs -P -> Parallel execution | || | GNU Parallel -> Advanced parallelization | || | Background jobs -> Async operations | || +----------------------------------------------------------+ || || Text Processing: || +----------------------------------------------------------+ || | awk -> Data extraction and reporting | || | sed -> Stream text editing | || | grep -> Pattern matching | || +----------------------------------------------------------+ || || Debugging: || +----------------------------------------------------------+ || | set -x -> Trace execution | || | bashdb -> Debugger | || | shellcheck -> Static analysis | || +----------------------------------------------------------+ || |+------------------------------------------------------------------+Practical Impact:
- Process large datasets efficiently
- Build complex automation pipelines
- Debug shell script issues
Common Mistakes & Anti-Patterns
Section titled “Common Mistakes & Anti-Patterns”1. Not Using Process Substitution
Section titled “1. Not Using Process Substitution”# WRONG: Using temp filesgrep pattern file > tempsort temprm temp
# CORRECT: Process substitutiongrep pattern file | sort2. Not Handling Signals Properly
Section titled “2. Not Handling Signals Properly”# WRONG: No cleanup on interruptwhile true; do workdone
# CORRECT: Handle signalstrap 'cleanup; exit' INT TERM3. Not Using ShellCheck
Section titled “3. Not Using ShellCheck”# WRONG: Writing scripts without linting# Hidden bugs
# CORRECT: Use shellcheckshellcheck myscript.shSummary
Section titled “Summary”In this chapter, you learned:
- ✅ Process management and signals
- ✅ Process substitution
- ✅ Advanced arrays and functions
- ✅ Error handling and debugging
- ✅ Parallel processing
- ✅ Text processing with awk/sed
Next Chapter
Section titled “Next Chapter”Chapter 48: Ansible for Linux Administration
Last Updated: February 2026