Skip to content

Instantly share code, notes, and snippets.

@belden
Last active May 22, 2026 18:38
Show Gist options
  • Select an option

  • Save belden/6f659a9ccaf624f0c52e5948112f42e0 to your computer and use it in GitHub Desktop.

Select an option

Save belden/6f659a9ccaf624f0c52e5948112f42e0 to your computer and use it in GitHub Desktop.
countdown - a `sleep` that tells you how much time is left
#!/usr/bin/env bash
set -e
if [[ ( $# -ne 1 ) || ! ( "$1" =~ ^[0-9]+$ ) ]]; then
echo "Usage: countdown <seconds>" >&2
exit 1
fi
end=$(( $(date +%s) + $1 ))
last=""
while [[ 0 ]]; do
remaining=$(( end - $(date +%s) ))
if [[ $remaining -le 0 ]]; then
break
fi
if read -rs -t 1 -n 1 _key < /dev/tty 2>/dev/null; then
if [[ "$last$_key" == ".." ]]; then
echo "ok, continuing!" > /dev/tty
break
else
last="$_key"
fi
printf '%d seconds remaining\n' "$remaining" > /dev/tty
else
last=""
fi
done
@belden

belden commented May 22, 2026

Copy link
Copy Markdown
Author

We write directly to /dev/tty so you can use this script in a pipeline with redirected stdout/stderr and not lose the feedback.

There's no explicit sleep in this script - read -t 1 does a 1 second timeout on the read, which allows it to double as "sleep 1 second" as well as "see if the user typed anything".

@belden

belden commented May 22, 2026

Copy link
Copy Markdown
Author

By popular request (@udipl suggested it!), pressing . twice in rapid succession will stop the timer immediately, and the script will exit without error.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment