March 2008
M T W T F S S
  1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31  

Small Bash Script to Count Seconds

So the short story is I got a small UPS for my tv, xbox and cable modem so that I won’t be interrupted by small power hiccups. I decided I wanted to know how long my CRT tv and xbox would continue while watching a movie so I needed something to count with while I unplugged the power to test it.

Now I’m sure others have written scripts and I could probably have just used the clock on the computer but I decided it couldn’t be too difficult to figure out how to write a script to do this. I knew that I basically had to just create a loop that would print a number increasing by one and then wait one second and repeat. I just had to find the right commands. About 10 to 15 minutes of searching later and I had this:

#!/bin/bash
#A very basic time counting script.
#init value of x
x=1
#make y 1 less than x
y=$((x-1))
echo "Counting from $y..." #Output what number we are beginning from
while [ $x -ge 0 ] #While $x is >= 0 (all the time)
do
sleep 1 #Wait one second
echo $x #Echo value of $x
x=$((x+1)) #Increase $x by 1
done

Some of the methods are a little different from what I am used to. To increase $x by 1, I am used to $x++. Bash is different I guess. There may be simpler ways to do this as well. If so, please leave a comment as I’m hopeful to learn.

Sample output:

$ ./count.sh
Counting from 0...
1
2
3
4
5

Also note this script will continue to run until the user types the escape sequence ‘Ctrl+C‘.

Some sources used to find what I needed:

5 comments to Small Bash Script to Count Seconds