Logo

Bash Scripting Guide - Advanced Topics

This guide covers advanced topics in Bash scripting, building on the foundational concepts presented earlier. Explore powerful features and techniques to enhance your Bash scripting skills.

Table of Contents

  1. Regular Expressions
  2. Process Management
  3. Error Handling
  4. Debugging

1. Regular Expressions

1.1 Overview

1.2 Using grep


# Example: Searching for lines containing "error" in a log file
grep "error" logfile.txt

1.3 sed (Stream Editor)


# Example: Replacing "apple" with "orange" in a file
sed 's/apple/orange/g' input.txt

1.4 awk Programming


# Example: Summing values in the second column of a CSV file
awk -F',' '{ sum += $2 } END { print sum }' data.csv

2. Process Management

2.1 Background Processes


# Example: Running a command in the background
long_running_command &

2.2 Signals


# Example: Handling the SIGTERM signal
trap 'echo "Received SIGTERM"; cleanup_function' TERM

2.3 Job Control


# Example: Running a command in the background and bringing it to the foreground
command &
fg

3. Error Handling

3.1 Exit Codes


# Example: Checking the exit code of the last command
if [ $? -eq 0 ]; then
  echo "Command succeeded"
else
  echo "Command failed"
fi

3.2 Trapping Signals


# Example: Gracefully handling SIGINT (Ctrl+C)
trap 'echo "Received SIGINT"; cleanup_function' INT

4. Debugging

4.1 set -x and set +x


# Example: Using set -x for debugging
set -x
# Your script commands here
set +x

4.2 PS4 Environment Variable


# Example: Customizing the PS4 prompt
PS4='Executing: '


Continue to Part 9: Best Practices.

Go back to Bash Scripting Guide.

Visit other Developer Guides.