Search code examples
basherror-handlingerror-logging

Bash scripting: log commands that produced errors?


I'm working on best practice for my bash scripts. At the top of each file, I put the following so it exits if any command produces an error:

set -o errexit

The problem is it doesn't help with debugging. I'm looking for a way of logging what command failed (i.e. the command and arguments that were run), and what line the error occurred on, and in which file.

What's a good way of doing this? E.g by a small set of commands at the top of each bash script? Perhaps having a central file that is used for all scripts to log such errors? What might those commands be?

Also, is it a good idea putting that in every script that needs it? Or should a single file with it be source'd into every script that needs it? Or perhaps there's a different way?


Solution

  • You have few options:

    • Use at the top of your script.sh file: #!/bin/bash -x
    • Use set -x option in script.sh
    • Use -x from command line: bash -x script.sh