Sobes.tech
Junior — Middle

How can an error be logged into a log file when executing a bash script?

sobes.tech AI

Answer from AI

To log an error in a log file when running a bash script, you can redirect the error stream (stderr) to a file. For example:

./script.sh 2>> error.log

Here, 2>> means appending errors to the file error.log.

If you want to log errors within the script itself, you can use the construct:

command 2>> error.log

Or redirect all script errors to a file by adding at the beginning of the script:

exec 2>> error.log

This will save all error messages for later analysis.