Skip to content

Instantly share code, notes, and snippets.

@russellbits
Created July 25, 2025 01:41
Show Gist options
  • Save russellbits/11e9b90a0b16a00b0fd748981bb571f3 to your computer and use it in GitHub Desktop.
Save russellbits/11e9b90a0b16a00b0fd748981bb571f3 to your computer and use it in GitHub Desktop.
Super Simple Command Line Timer
#!/bin/bash
# Timer script for MacOS
# Usage: timer [-s HHMMSS]
# Default: 25 minutes (00:25:00)
# Function to display usage
usage() {
echo "Usage: timer [-s HHMMSS]"
echo " -s HHMMSS Set timer to HH hours, MM minutes, SS seconds (e.g., -s 012530 for 1h 25m 30s)"
echo " Default: 25 minutes (00:25:00)"
exit 1
}
# Function to validate time format
validate_time() {
local time_str=$1
if [[ ! $time_str =~ ^[0-9]{6}$ ]]; then
echo "Error: Time must be exactly 6 digits (HHMMSS)"
exit 1
fi
local hours=${time_str:0:2}
local minutes=${time_str:2:2}
local seconds=${time_str:4:2}
if [ $minutes -gt 59 ] || [ $seconds -gt 59 ]; then
echo "Error: Invalid time format. Minutes and seconds must be 00-59"
exit 1
fi
}
# Function to format time display
format_time() {
local total_seconds=$1
local hours=$((total_seconds / 3600))
local minutes=$(((total_seconds % 3600) / 60))
local seconds=$((total_seconds % 60))
printf "%02d:%02d:%02d" $hours $minutes $seconds
}
# Parse command line arguments
CUSTOM_TIME=""
while getopts "s:h" opt; do
case $opt in
s)
CUSTOM_TIME=$OPTARG
validate_time $CUSTOM_TIME
;;
h)
usage
;;
\?)
echo "Invalid option: -$OPTARG" >&2
usage
;;
esac
done
# Set default or custom time
if [ -n "$CUSTOM_TIME" ]; then
hours=${CUSTOM_TIME:0:2}
minutes=${CUSTOM_TIME:2:2}
seconds=${CUSTOM_TIME:4:2}
# Convert to total seconds
total_seconds=$((hours * 3600 + minutes * 60 + seconds))
else
# Default: 25 minutes
total_seconds=$((25 * 60))
fi
# Check if total time is 0
if [ $total_seconds -eq 0 ]; then
echo "Timer set to 00:00:00 - nothing to count down!"
exit 0
fi
echo "Timer started: $(format_time $total_seconds)"
echo ""
# Main countdown loop
while [ $total_seconds -gt 0 ]; do
# Display current time and move cursor back to beginning of line
printf "\r$(format_time $total_seconds)"
sleep 1
((total_seconds--))
done
# Timer finished
printf "\r00:00:00"
echo "⏰ Time's up!"
# Optional: Play system sound (macOS)
afplay /System/Library/Sounds/Glass.aiff 2>/dev/null || echo "🔔 TIMER FINISHED!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment