Show command executed along with output in log file

13,047

Solution 1

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.

Solution 2

You could look into the script tool, which will save the entire terminal session until you exit the program you call (which by default would be a shell). Example use-case:

~/:$ script test.output
Script started, output file is test.output
~/:$ mkdir example
~/:$ cd example
~/example/:$ touch new\ file.txt
~/example:/$ ls
new file.txt
~/example:/$ exit

The contents of the file test.output would then be as follows:

Script started on Mon Jun 25 16:24:28 2012
~/:$ mkdir example
~/:$ cd example
~/example/:$ touch new\ file.txt
~/example/:$ ls
new file.txt
~/example/:$ exit

Script done on Mon Jun 25 16:24:41 2012

Be aware that this file is a complete terminal transcript, so any backspaces will show up as ^H or ^? (or whatever your terminal's backspace is).

Share:
13,047

Related videos on Youtube

Brandon Kreisel
Author by

Brandon Kreisel

Updated on September 18, 2022

Comments

  • Brandon Kreisel
    Brandon Kreisel over 1 year

    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?