Shell – Show command executed along with output in log file

io-redirectionlogsshell-script

Is there a quick and dirty way to not only log the output of a shell file but the commands used inside as well?

For example:

whoami > who.dmp

would output a file that contained something like:

my_username

For a longer shell file, what is the most effective way to display the command that caused the result in the log file as well

Ex:

log.txt
###############

echo whoami  <- I want this to show in the file as well
my_username

time   <- I want this to show in the file as well

real    0m0.00s
user    0m0.00s
sys     0m0.00s

Is there a way to do this without hard-coding exporting the command into the output file every single time?

Best Answer

Using the shell built-in set -x is probably the cheap-and-dirty way to do this. In shell scripts you will often see a line like:

#set -x

Which someone left behind by just commenting it out. I think you could use that at the interactive command line, but you may not like what it does there.

Related Question