How To Ideas | How To Articles | How To Tutorials


0

How to create a Terminal Clock using Shell Script


date command displays current date and time to the Terminal and we can use this command to recursively display time every second on Terminal which will look like a Terminal Clock. In this tutorial, I will show you how to create a Shell Script which will make the terminal to show system time every second like a clock.

Default output of date command prints result in the format shown in following image.

date command

date command

But if we use +%r option with date command, the output format changes to format of the system locale as shown in following image.

date command to show time in the format of the system locale

date command to show time in the format of the system locale

Instructions:

  1. Tell the Terminal to use bash to execute the commands of the script file.
    #!/bin/bash
  2. Now clear the Terminal using clear command so that output of the date command will shown at the top of the Terminal window.
    clear
  3. Now using a while loop which will run infinitely print the time using the following command in which echo command is used with -e option which enable interpretation of backslash escapes (\b) and \c option prevent the echo command to enter a newline character.
    echo -e "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b`date +%r` \c"
  4. We have to sleep the Shell for a second before next iteration of while loop takes place. So, the full while loop looks like
    while true
    do
        echo -e "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b`date +%r` \c"
        sleep 1
    done

Following image is a screenshot of the working sample script.

Terminal Clock Output

Terminal Clock Output

You can download the sample script file here.

Filed in: Shell Scripting Tags: , , , , , ,

Leave a Reply

Submit Comment



© 6758 How To Ideas. All rights reserved.
Proudly designed by Theme Junkie.