Sobes.tech
Junior — Middle

What methods can be used to detect and handle errors when executing bash scripts?

sobes.tech AI

Answer from AI

The following methods are used to detect and handle errors in bash scripts:

  1. Checking the return code of commands — after executing a command, the variable $? is checked. If it is not equal to 0, an error has occurred.
command
if [ $? -ne 0 ]; then
  echo "Error executing command"
fi
  1. set -e — an option that causes the script to terminate when any command fails.
set -e
command1
command2 # if command1 fails, the script will stop
  1. trap — allows catching signals and errors, and executing handlers.
trap 'echo "An error occurred"; exit 1' ERR
  1. Using conditional operators and try-catch constructs (via functions) for more complex error handling.

  2. Outputting debug information with set -x to track command execution.

Example with error handling and message output:

#!/bin/bash
set -e
trap 'echo "Error at line $LINENO"' ERR

command1
command2

By combining these methods, errors in bash scripts can be effectively detected and handled.