Documenting Unix commands on the command line

command lineredirectionshellunix

I would like to append both the last command and the output of the last command to a text file for the purpose of a tutorial.

For example: After I do an ls in my home directory I see this on the screen

bguiz@sheen:~$ ls
Desktop     Music    Documents

I want to then be able to enter a single command which will append the following to a textfile named cmd.txt

$ ls
Desktop     Music    Documents

The idea is that each time I enter a command, I can log both the command itself and its output to the same file, and after several commands, it will demonstrate a particular series of commands. I know this can be done manually – but why do that if there's an easy alternative, right?

This is what I've cooked up so far:

echo -n "\$ " >> cmd.txt; echo !-1:p >> cmd.txt; !-1 >> cmd.txt

It works, but is rather clunky, and has several gotchas such as not being able to preserve the exact screen formatting.

Is the a more elegant solution?

Thank you for the answers so far, but I have a requiement that it needs to work with pipe, e.g.:

ls -lart | grep ^d

Needs to get this appended in the file:

$ ls -lart | grep ^d
drwx------ 14 bguiz staff   4096 2010-03-03 15:52 .cache
drwx------  5 bguiz staff   4096 2010-03-03 09:38 .ssh

Best Answer

[script.ksh] run with "script.ksh ls"



if [[ $# -eq 0 ]];then
  print "no command to run"

# dump command being run to file
echo $@ >> $OUTPUT

# run command and output stdout to the screen and file
$@ | tee -a $OUTPUT