brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: script -qc runs one command as if it had a terminal

Terminal
~/tips/tip-script-qc-dev-null-fake-tty

script -qc 'ls --color=auto -d .' /dev/null | cat -v

Runs a command inside a pseudo-terminal, so it behaves as if you ran it by hand.

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 with tr -d '\r' before you compare or parse the text.
  • The exit code of script is not the command’s by default. Add -e (--return) and it returns the exit status of the child. script -qec 'exit 3' /dev/null exited 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

More Terminal tips "copyOnSelect": true "multiLinePasteWarning": true, tput civis ioreg -rn AppleSmartBattery | grep CycleCount Terminal can save your windows and tabs as a window group All Terminal tips (124) All topics

Link