Some programs change their behaviour when the output goes into a pipe: colours vanish, progress bars disappear, a prompt is skipped. They ask whether they are talking to a terminal and the answer is no. script is better known for recording sessions, but it also gives a single command a terminal to talk to.
script -qc 'ls --color=auto -d .' /dev/null | cat -v
The manual describes -c as running the command rather than an interactive shell, and -q as being quiet, with no start and done messages. The last argument is the file the recording goes to. Pointing it at /dev/null throws the recording away and leaves only the output. On util-linux 2.39.3, ls --color=auto -d . piped into cat -v printed a plain .. Through script the escape codes for colour showed up:
^[[0m^[[01;34m.^[[0m^M
The same effect shows in a test. Inside a pipe, test -t 1 && echo tty || echo notty printed notty. Run through script -qc, it printed tty.
Two details are worth knowing:
- The output ends in
^M, a carriage return, because a terminal translates line endings. Strip it withtr -d '\r'before you compare or parse the text. - The exit code of
scriptis not the command’s by default. Add-e(--return) and it returns the exit status of the child.script -qec 'exit 3' /dev/nullexited with 3.
One caveat: the manual says that without a file name, the recording goes to a file called typescript in the current folder. In a script, always pass /dev/null or a real path, or you leave files behind.
Further reading: script(1) manual