Sobes.tech
Middle

How do you handle user errors in bash?

sobes.tech AI

Answer from AI

In bash, user errors are mainly handled using:

  • Command exit codes: Each command returns an exit status. 0 usually indicates success, any other value indicates an error.
  • Conditional constructs: if, elif, else are used to check exit codes.
  • Logical operators: && (and), || (or) allow executing commands based on the success/failure of previous commands.
  • Output redirection: > (stdout), 2> (stderr), &> (stdout and stderr).
  • Traps: Allow executing a command upon receiving a signal or script termination.

Examples:

#!/bin/bash

# Check exit code
if ! command_that_might_fail; then
  echo "Command execution error!" >&2 # Redirect to stderr
  exit 1 # Exit script with error code
fi

# Logical operator &&
command_successful && echo "Command executed successfully" || echo "Command failed"

# Trap for handling SIGINT (Ctrl+C)
trap 'echo "Interrupt signal received. Exiting..."; exit 1' SIGINT

# Redirect errors and output message
if command_with_errors 2> error.log; then
  echo "Command completed without errors"
else
  echo "Errors detected. Details in error.log"
fi

To increase script reliability, the following are also used:

  • set -e: The script exits upon any command failure (except checks in if and while).
  • set -u: Variables must be defined before use.
  • set -o pipefail: The exit code of a pipeline becomes the exit code of the last command that failed (not always the last command in the pipeline).
#!/bin/bash

set -euo pipefail

# This script will exit if "undefined_var" is not set
echo "$undefined_var"

# This script will exit if "failing_command" returns a non-zero exit code
failing_command

Using functions and arguments:

#!/bin/bash

# Function with argument check
validate_args() {
  if [ $# -ne 2 ]; then
    echo "Usage: $0 <argument1> <argument2>" >&2
    exit 1
  fi
}

validate_args "$@"