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: read -s -p hides what you type, and -t gives up after a timeout

Shell
~/tips/tip-shell-read-s-t-prompt

read -r -s -p "Token: " token; echo

Prompts for input without echoing it and gives up after a set number of seconds.

When a script has to ask for something, read can do more than the plain form most of us type.

A few options cover most prompts. -p shows a prompt, but only if input comes from a terminal. -s is silent mode, so characters are not echoed. -t sets a timeout in seconds, after which read fails. The manual says it saves any partial input and returns a status greater than 128. Add -r so backslashes in the input are kept as typed.

read -r -s -p "Token: " token; echo
read -r -t 10 -p "Continue? [y/N] " answer || answer=n

The bare echo after the first line prints the newline that silent mode swallows. The second line treats a timeout like “no”, which is a sensible default for a script that might run unattended. The timeout can be a decimal, so -t 0.5 is allowed too.

A full example with a default answer looks like this:

read -r -t 10 -p "Delete old backups? [y/N] " answer || answer=n
case "$answer" in
  y|Y) echo "deleting" ;;
  *)   echo "skipped" ;;
esac

A timeout, an empty answer or anything else than y all end up at “skipped”, so a stray keypress never deletes anything.

One thing to keep in mind with -s: it only hides the typing. The value is now in a shell variable, and if you pass it to a program as an argument, other users on the machine can see it in the output of ps. For a secret that has to reach another program, an environment variable or a file with tight permissions is the better route.

Further reading: bash(1) manual page

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