Sobes.tech
Middle

How do you handle errors in bash scripts?

sobes.tech AI

Answer from AI

  • set -e: Causes the script to exit immediately if any command exits with a non-zero status.
  • set -u: Causes the script to exit if an uninitialized variable is used.
  • set -o pipefail: Causes a pipeline to return a non-zero status if any command in the pipeline fails.
  • Error handling with traps (trap):
#!/bin/bash

# Function to handle errors
handle_error() {
  local exit_code=$?
  local line_num=$1
  echo "Error on line $line_num with exit code $exit_code" >&2
  exit $exit_code
}

# Setting traps to catch EXIT and ERR signals
trap 'handle_error $LINENO' ERR
trap 'echo "Script finished"; exit 0' EXIT

# Example of a poorly working command
ls /nonexistent/path

echo "This line will not be executed if the previous command fails"
  • Checking the exit code of a command:
#!/bin/bash

if ! command_that_might_fail; then
  echo "Command failed" >&2
  exit 1
fi
  • Using process substitutions for error handling in pipelines:
#!/bin/bash

# Example of a pipeline with an error
ls /nonexistent/path | grep "something" > /dev/null

# Checking the exit status of the last element in the pipeline
if [ ${PIPESTATUS[0]} -ne 0 ]; then
  echo "The first command in the pipeline failed" >&2
  exit 1
fi