Capturing command line data output

Monitoring With Linux Command Output Capture
 

When operating with the command line in Linux and UNIX, it is not unusual for the output from your command to scroll off the screen before you can read it.  This can be frustrating when you are trying to work out an issue, or check the results of your command.

One solution is to capture the output to a file with utilities, then you can read the file and use other methods such as grep, or vi, to search for specific output.

The first capture utility is the "tee" command. 
You simply pipe the output from your command to the tee command by adding "| tee " after the command.  Everything sent to standard-out is sent to the file specified with tee.  Be aware, however, that output sent to other channels, such as standard-error, are not captured.  For example, suppose you run "ls -l file.1 file.2 file.3 | tee /tmp/file.list".  Also, let’s say that file.1 and file.2 exist, but not file.3.  On your screen, you will see a message that file.3 could not be found.  However, since this is an error, and the list command send that to standard-error, the tee command will not capture it.  In this case, the /tmp/file.list, will have the lines with the information for file.1, and file.2, only.

If you need to capture the output from standard-error to your tee file, then you need to redirect standard-error to standard-out.  This is done by adding "2>&1" after your command, and before the pipe.  So, "ls -l file.1 file.2 file.3 2>&1 | tee /tmp/file.list" will capture both standard-error and standard-out to the /tmp/file.list.

The other utility is the "script" utility.   (Availability may depend on your flavor of Linux.)
This one captures everything that is output to the screen, regardless of what channel it is on, to the file.  It also captures what you type.  In the simplest form, it is simply "script ".  So, "script /tmp/file.list" will enter the script utility, and send all output to the /tmp/file.list file.  After entering the script utility you will get another command prompt.  Enter your commands as usual.  What you type on the command line will also be captured to the file.  So, using the list command from before, "ls -l file.1 file.2 file.3" will not only show the listing for file.1 and file.2, and the error that file.3 is not found, it will also capture the command "ls -l file.1 file.2 file.3", as well as the command prompt after the output.  In other words, using "script" you get a complete transcript of what was typed, and the results that were generated.

One thing to be aware of when using script, is that you are entering a sub-shell.  Once you have finished with what you want to capture, remember to exit the sub-shell, using the "exit" command.  The script utility will respond that it has ended, and the file name that the output was saved to (the one that you specified when you called "script").

Dave.

Exit mobile version