Last active
May 22, 2026 18:38
-
-
Save belden/6f659a9ccaf624f0c52e5948112f42e0 to your computer and use it in GitHub Desktop.
countdown - a `sleep` that tells you how much time is left
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/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 |
Author
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
We write directly to
/dev/ttyso you can use this script in a pipeline with redirected stdout/stderr and not lose the feedback.There's no explicit
sleepin this script -read -t 1does a 1 second timeout on theread, which allows it to double as "sleep 1 second" as well as "see if the user typed anything".