Skip to content

Instantly share code, notes, and snippets.

@chawkins88
Last active October 6, 2017 16:09
Show Gist options
  • Save chawkins88/289d2093a6eefab8a2ffe19c8bd4d52c to your computer and use it in GitHub Desktop.
Save chawkins88/289d2093a6eefab8a2ffe19c8bd4d52c to your computer and use it in GitHub Desktop.
in line counter for looping bash script
#!/bin/bash
#
# Enhanced version of the excellent original script here:
# https://www.cyberciti.biz/faq/how-to-display-countdown-timer-in-bash-shell-script-running-on-linuxunix
#
# This script will continuously loop on a set interval and run whatever command you put on line 10.
# It will display a timer and count down the seconds until the next loop.
#
cmd="/some/script/or/command"
# use 1 min as default value. Ovverride by setting INTERVAL_MINUTES env var.
if [ -z $INTERVAL_MINUTES ]; then
INTERVAL_MINUTES=1
fi
while true; do
# how long to wait
SECONDS=$((INTERVAL_MINUTES * 60))
# get current position on screen
exec < /dev/tty
oldstty=$(stty -g)
stty raw -echo min 0
# on my system, the following line can be replaced by the line below it
echo -en "\033[6n" > /dev/tty
# tput u7 > /dev/tty # when TERM=xterm (and relatives)
IFS=';' read -r -d R -a pos
stty $oldstty
# change from one-based to zero based so they work with: tput cup $row $col
row=$((${pos[0]:2} - 1)) # strip off the esc-[
col=$((${pos[1]} - 1))
# offset the counter message so it's easier to see
let row=$row+1
let col=$col+2
msg="Counting down to the next run... "
count=$SECONDS
# set cursor position
tput cup $row $col
echo -n "$msg"
msg_length=${#msg}
counter_column=$(( msg_length+$col+2 ))
# output our timer
while [[ $count > 0 ]]
do
# clear the previous value
tput cup $row $counter_column
echo -n " "
# write the new value
tput cup $row $counter_column
echo -n $count
sleep 1
let count=$count-1
done
echo
echo
$cmd || echo "run failed, trying again in $INTERVAL_MINUTES min."
echo
unset count
done
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment