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: [ -t 1 ] tells a shell script whether a person is watching

Shell
~/tips/tip-shell-test-t-terminal

if [ -t 1 ]; then

Use colours and progress output only when output goes to a terminal.

Colour codes look nice in a terminal and turn into junk like ^[[31m in a log file. A script can check where its output goes and decide for itself.

-t tests whether a file descriptor is connected to a terminal. Descriptor 1 is stdout:

if [ -t 1 ]; then
  red=$'\e[31m' reset=$'\e[0m'
else
  red='' reset=''
fi
echo "${red}disk almost full${reset}"

Run it by hand and the warning is red. Pipe it into less, redirect it to a file or run it from cron, and the codes are gone.

[ -t 0 ] asks the same about stdin, which tells you whether you can ask the user a question or whether input comes from a pipe. I’d use that to skip a confirmation prompt when nobody is there to answer it.

Do not use it as the only switch for behaviour that matters. A script run through ssh host script without -t sees no terminal either, even with you looking at the output. For colour, it is also polite to honour the NO_COLOR variable that many tools respect.

Further reading: Bash manual: Bash Conditional Expressions, NO_COLOR

More Shell tips zmv -n '(*).log' '$1.txt' zoxide query -ls project f=$(mktemp --suffix=.json) shopt globskipdots echo $EPOCHSECONDS All Shell tips (78) All topics

Link