Simple CLI Timer
Ever wanted to run a super simple timer directly from the command line? Oh, you havenβt? Well, you can still read this anyway since you might learn something π.
I built a super basic implementation with a while loop and sleep
.
#!/usr/bin/env bash
β
# Check if the user has input a duration for the timer
if [ -z "$1" ]; then
echo "Usage: $0 <minutes> [message]"
exit 1
fi
β
# User settings
duration="$1"
message=${2:-"Timer done!"}
β
# Record the start time
start_time=$(date +%s)
β
# Run the timer
while true; do
current_time=$(date +%s)
elapsed_time=$((current_time - start_time))
remaining_time=$((duration * 60 - elapsed_time))
β
# Show the notification when the time is done
if [ $remaining_time -le 0 ]; then
osascript -e "display notification \"$message\" with title \"Time is Up!\" sound name \"Submarine\""
echo -e "\rTime is up!"
exit 0
fi
β
# Print the time remaining
if [ $remaining_time -ge 60 ]; then
minutes=$((remaining_time / 60))
seconds=$((remaining_time % 60))
β
# Escape sequence to clear the line
clr="\033[2K"
β
if [ $seconds -eq 0 ]; then
echo -ne "$clr\r${minutes}m "
else
echo -ne "$clr\r${minutes}m ${seconds}s "
fi
else
echo -ne "$clr\r${remaining_time}s "
fi
β
# Tick the clock
sleep 1
done