script(1) command
script(1) command on Unix or Linux aims to make typescript of terminal session (Reference: Unix Help or
man 1 script
). Its implementation is based on pseudoterminal. Here’s a diagram that shows how script is implemented.
For example,
$script -c "echo helloworld"
will run echo helloword
to print helloword
on terminal (stdout). In addition, it will produce a typescript file that is a copy of everything printed on terminal of the command. In this case, typescript likes below Script started on Tue 19 May 2015 10:34:26 BST
helloworld
Script done on Tue 19 May 2015 10:34:26 BST
one use case
Scenario
If we have a command that will show a progress bar (like
scp
) and we need to write a test case for this command to test if the progress bar works as expected, we can not easily capture its output by redirecting its stdout to a file because usually this command will check if the file descriptor for output is a terminal or not by isatty
function.if(isatty(fd))
{
// show a progress bar
}
With redirection like
$cmd > file
, stdout points to a file. Therefore, isatty
function will return 0. Finally progress bar is hidden. That’s not what we expect.Solution
script -c "cmd" | sed "s/\\r/\\n/g" > prog.txt
With
script
, the output of cmd
is still a terminal (stdout) and so we can capture its output. Besides, through sed
, we replace carriage return (\r) by line feed (\n), and then every print by cmd
can be captured.
Now
prog.txt
will record the output of progress bar in this cmd
command. That’s what we expected.
No comments :
Post a Comment