We may often come across situations while writing scripts wherein we need to wait for an event to complete or use the sleep command. It would be useful if you could display the amount of time remaining before the execution of the script would resume.
Given below is a short script that would display a running timer for 10 seconds using a simple while loop and the sleep command.
[root@cent6 ~]# cat count.sh
#!/bin/bash
i=10
echo "timer starting for $i seconds"
while [ $i -gt 0 ]
do
echo -ne "\t $i \033[0K\r"
sleep 1
i=$[$i - 1]
done
echo "counter complete"
The real magic of the counter comes from the echo statement. Here is a description of what we've used in the echo statement:
-n will not output the trailing newline. So that saves me from going to a new line each time I echo something.
-e will allow me to interpret backslash escape symbols.
\033[OK represents an end of line which cleans the rest of line if there are any characters left from previous output
\r is a carriage return which moves the cursor to the beginning of the line.
The output of the script is a cool neat timer that runs for 10 seconds.
No comments:
Post a Comment