Show time elapsed with script

I made some improvements. My 2nd parameter is sent to a text file where gxmessage can display the message.

#!/bin/bash
# Much help from https://ubuntu-mate.community
# tkn, pavlos_kairus, and charles-nix

soundfile="/usr/share/sounds/My_Sounds/Alarm-sound-buzzer.mp3"

#clear
#amixer -D pulse sset Master 50% > /dev/null 2>&1
if [ -f "$soundfile" ];
then
     echo "Soundfile is present."
else
  echo -e "File $soundfile does NOT exist.\n\nProgram will now exit.\n"
  exit
fi
sleep 2
#clear

# Below, I cleaned it up a bit by using a  "here document"

[ -z "$2" ] && {
echo 
echo -e "   Error!! No time value given and/or message specified !!"
echo
echo -e "   Alarm Program 2018"
echo
echo -e "   alarm.sh [time value in seconds] Message in double Quotes"; 
echo -e "   alarm 5m   = 5 minute alarm"
echo -e "   alarm 5h   = 5 hour alarm"
echo -e "   alarm 5d   = 5 day alarm"
echo -e "   alarm 1.5m = 1 minute 30 seconds alarm"
echo 
echo -e "   alarm.sh 1m "\"Tea is ready."\""  

echo 
exit 1; }

# alternative way to do colors
Reset=$( tput sgr0    ) ; Bl=$( tput blink   ) ; Gr=$( tput setaf 2 )

echo  -e "${Gr}${Bl}TIMER COUNTING DOWN to $1${Reset}"


# countdown display
# below is the part you are interested in
# it replaces your "sleep" command


#this converts days,hours,months to seconds
case "$1" in
*d ) fact=86400 ;;
*h ) fact=3600  ;;
*m ) fact=60    ;;
*  ) fact=1     ;;
esac
(( period = ${1/[a-z]/} * fact ))


#this calculates the endtime based on 'now'
start=$( date +"%s" ) ; (( finish = start + period ))


# this is the counter,  based around charles-nix's counter format idea 
while (( period >= 0 ))
do
       echo -ne "$(date -u --date @${period} +%H:%M:%S)\t\t\r";
       (( period = finish - $( date +%s ) )) 2>/dev/null
done	    	 


# Fade-in process:
#you used curly brackets but you probably wanted  parenthesis
(
    for ((volume = 35; volume <= 40; volume += 2)); do
        amixer -D pulse sset Master ${volume}% > /dev/null
        sleep .5
    done
) &

cvlc --play-and-exit "$soundfile" &> /dev/null
clear
echo $2 > /home/andy/Downloads/test.txt
gxmessage -geometry 1100x100 -fg red -font 'sans 30' -timeout 3 -file /home/andy/Downloads/test.txt
rm /home/andy/Downloads/test.txt

This works well if just inputting seconds.

But it gets more complicated when you want to input minutes or hours.

Is there a way to simplify that?

# To use, countdown Number of seconds
# 2 hours countdown "$((2 * 60 * 60))"
# 5 minutes countdown      "$((5 * 60))"

countdown() {
start="$(( $(date '+%s') + $1))"
while [ $start -ge $(date +%s) ]; do
time="$(( $start - $(date +%s) ))"
printf '%s\r' "$(date -u -d "@$time" +%H:%M:%S)"
sleep 0.1
done
printf "Tea is ready.\n"
}

I would use countdown 300 for 5 min and countdown 7200 for 2 hours.

countdown $((1*10)) works for me.

1 Like