At times system administrators and developers need to use many, complex and lengthy commands in order to perform a critical task. Most of the users will copy those commands and output generated by those respective commands in a text file for review or future reference. Of course, “history” feature of the shell will help you in getting the list of commands used in the past but it won’t help in getting the output generated for those commands.
Luckily there exists a simple and time-saving utility known as a script that does this job for you. The script command does its business quietly by running in the background. This utility is a must when only command line interface is available for the servers you manage. This article explores its usage with examples.
Starting recording activities of a terminal session
Just type “script” on the command line:
A startup message “Script started, file is typescript” is displayed as follows:
Now script command starts recording the user commands in the background until a user enters “exit” or press Control-D to stop the recording.
Everything between the “script” and the “exit” command is logged to a file in the current directory by default. Let us run few commands and see how the script stores the commands and corresponding output as follows:
In the above screenshot, the script command is run with commands “free –h” and “vmstat”. Once the user quit from the recording by typing “exit” or Ctrl+D, All the commands executed and their respective output is recorded in the file “typescript” in the present working directory. So simple yet amazing!
Recording activities into a file
It is a good practice to store script recording session into a user defined a file with some timestamp so that it will be useful to refer it at a later point in time. For this, the script command needs to be executed by providing the desired file name as argument follows:$ script <file_name>
Below screenshot captures how the recording is stored in the user-supplied log file:
Appending recording activities into an existing file
It may be required to append the recording history into an existing log file. For this, the script command needs to be executed by providing the file name with “-a” option indicating append operation.$ script –a <existing_file_name>
More options can be obtained from script man page.
It is not recommended to run the script command in non-interactive shells. The script command stores everything (control characters like linefeeds) in the log file. If the environment variable SHELL is set, the shell is forked by the script. If not set, Bourne shell is assumed as default. If no log file name is provided to script, a default file, typescript will be used. The script command complains if the log file provided cannot be created. If the given the log file already exists and “–a” option is not used then old file will be overwritten.