Easy way to redirect log in shell

If you write a bash script file, and want to keep the running log, what is the easy way?

You can just echo the log messages to stderr or stdout, and add redirection arguments when calling the script.

You can also define one log function and call it to log messages in the whole script, but it is a little complex.

Recently, I learn a easy way to log messages for simple shell script: using exec builtin command.


# !/bin/env bash

# add this at the begnning of script
exec > /tmp/debug.log 2>&1

# other commands may echo to stderr or stdout
if [ ... ]; then
    echo "success"
else
    echo "fail"
fi

Here is the help for exec command:

exec: exec [-cl] [-a name] [command [arguments ...]] [redirection ...]
    Replace the shell with the given command.

    Execute COMMAND, replacing this shell with the specified program.
    ARGUMENTS become the arguments to COMMAND.  *If COMMAND is not specified,
    any redirections take effect in the current shell.*

    Options:
      -a name	pass NAME as the zeroth argument to COMMAND
      -c	execute COMMAND with an empty environment
      -l	place a dash in the zeroth argument to COMMAND

    If the command cannot be executed, a non-interactive shell exits, unless
    the shell option `execfail' is set.

    Exit Status:
    Returns success unless COMMAND is not found or a redirection error occurs.

Check this message: If COMMAND is not specified, any redirections take effect in the current shell.

So it is very useful for simple script just run several commands for workflow, and especially very convenient to embed script in config files.

#Shell #Bash #Linux