Skip to content

Advanced_bash

This chapter covers advanced bash scripting techniques for automation.


Terminal window
# Run in background
command &
./script.sh &
# Wait for background process
wait $PID
# Jobs control
jobs
fg %1
bg %1
Ctrl+Z # Suspend
Terminal window
# Trap signals
trap 'echo "Caught SIGINT"' INT
trap 'cleanup' EXIT
# Common signals
# SIGINT (2) - Ctrl+C
# SIGTERM (15) - Graceful termination
# SIGKILL (9) - Force kill
# SIGHUP (1) - Hangup

Terminal window
# Compare files
diff <(sort file1) <(sort file2)
# While with process substitution
while read line; do
process $line
done < <(command)
# Read from multiple files
paste <(cut -f1 file1) <(cut -f2 file2)

Terminal window
# Requires bash 4+
declare -A users
users[admin]=root
users[nginx]=www-data
# List keys/values
echo ${!users[@]}
echo ${users[@]}
Terminal window
# Slicing
${array[@]:start:length}
# Search and replace in array
${array[@]/old/new}
# Conditional filter
${array[@]/*pattern*/}

Terminal window
# Return status
check_service() {
systemctl is-active $1
return $?
}
# Return data via stdout
get_users() {
awk -F: '$3 >= 1000 {print $1}' /etc/passwd
}
users=$(get_users)
# Using global variable
RESULT=""
store_result() {
RESULT="computed value"
}

Terminal window
# Exit with status
exit 0 # Success
exit 1 # Error
exit 2 # Misuse
exit 126 # Not executable
exit 127 # Command not found
# Check exit status
command
if [ $? -eq 0 ]; then
echo "Success"
fi
# Set -e (exit on error)
set -e
command || { echo "Failed"; exit 1; }
Terminal window
# Verbose mode
set -v
# Debug mode
set -x
# Track errors
set -o errtrace
set -o pipefail
# Combined
set -euo pipefail

Terminal window
# Parallel execution
ls *.log | xargs -P 4 -I {} gzip {}
# With GNU parallel
cat hosts | parallel -j 4 ssh {} 'uptime'
Terminal window
# Run in parallel
for server in server1 server2 server3; do
ssh $server 'apt update' &
done
wait
# Limit parallel jobs
sem -j 4 ./process.sh

Terminal window
# Print specific columns
awk '{print $1, $3}' file
# Field separator
awk -F: '{print $1}' /etc/passwd
# Conditional
awk '$3 > 1000 {print $1}' /etc/passwd
# Operations
awk '{sum+=$1} END {print sum}' file
Terminal window
# Replace
sed 's/old/new/g' file
sed -i 's/old/new/g' file
# Delete lines
sed '/pattern/d' file
# Print lines
sed -n '1,10p' file
sed -n '/start/,/end/p' file

Terminal window
# Avoid eval
# Sanitize input
# Use quotes for variables
# Don't use backticks (use $())
# Check file permissions
# Validate arguments

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

Chapter 48: Ansible for Linux Administration


Last Updated: February 2026