Skip to content

Instantly share code, notes, and snippets.

@xantiagoma
Last active January 7, 2025 00:31
Show Gist options
  • Save xantiagoma/a7ad072b34db33bc767fbc1aed3bb5d3 to your computer and use it in GitHub Desktop.
Save xantiagoma/a7ad072b34db33bc767fbc1aed3bb5d3 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Default text and settings
custom_text="⏱️"
keep_last=false
show_done=true
done_text=""
# Parse arguments
while [[ $# -gt 0 ]]; do
case "$1" in
--text)
if [[ -z "$2" || "$2" == --* ]]; then
echo "Error: --text requires a value"
exit 1
fi
custom_text="$2"
shift 2
;;
--keep-last)
keep_last=true
shift
;;
--done-text)
if [[ -z "$2" || "$2" == --* ]]; then
echo "Error: --done-text requires a value"
exit 1
fi
done_text="$2"
shift 2
;;
--remove-done)
show_done=false
shift
;;
-*)
echo "Error: Unknown option $1"
exit 1
;;
*)
if [[ "$1" =~ ^[0-9]+$ ]]; then
seconds=$1
shift
else
echo "Error: Invalid number of seconds: $1"
exit 1
fi
;;
esac
done
# Validate that seconds was provided
if [ -z "$seconds" ]; then
echo "Error: Number of seconds is required"
echo "Usage: countdown <seconds> [--text \"Custom message\"] [--keep-last] [--done-text \"Done message\"]"
exit 1
fi
# Store initial seconds for --print-duration
initial_seconds=$seconds
# Countdown loop
while [ $seconds -gt 0 ]; do
printf "\r%s: %02d:%02d" "$custom_text" $((seconds / 60)) $((seconds % 60))
sleep 1
((seconds--))
done
# Clean up the last line unless --keep-last is specified
if [ "$keep_last" = false ]; then
printf "\r%*s\r" $((${#custom_text} + 7)) ""
else
echo
fi
# Simplify the final output logic
if [ "$show_done" = true ]; then
printf "%s %02d:%02d\n" "$done_text" $((initial_seconds / 60)) $((initial_seconds % 60))
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment