How to Print Time in Bash [2 Quick Methods]

Printing current time is useful for logging purposes, timing operations as well as displaying real-time information. Using the date command with proper format specifiers one can display the time in various formats such as hours, minutes, and seconds, either in 24-hour or 12-hour clock notation. In this article, I am going to demonstrate how to print time in Bash and customize it.

Key Takeaways

  • Printing time and parts of time (like-Only Hour or Minute).
  • Printing time using timedatectl command.
  • Learning about system time and local time.

Free Downloads

2 Methods of Printing Time in Bash

There are two commands in Bash for obtaining the current date and time: date and timedatectl. The date command is specifically designed for printing time and date information. However, the timedatectl is another command that can also provide the current time.

You can read the Comparative Analysis of Methods to find the easy one for you.

Method 1: Printing Time Using the “date” Command

The date command by default prints the current date and time. Fortunately, it provides many options and format specifiers that allow users to print the current time without printing the date. The following script shows you how to do that.

Steps to Follow >

❶ At first, launch an Ubuntu Terminal.

❷ Write the following command to open a time.sh file in the built-in nano editor:

nano date.sh
EXPLANATION
  • nano: Opens a file in the Nano text editor.
  • time.sh: Name of the file.
Creating Bash script file for Bash print time❸ Copy the following script and paste it into nano. Press CTRL+O and ENTER to save the file; CTRL+X to exit. Alternatively, copy the following script. Paste the script in a text editor and save it as .sh file.
#!/bin/bash

today=$(date)
echo "Today's date: $today"

time_with_seconds=$(date +%T)
echo "Current time (with seconds): $time_with_seconds"

time_without_seconds=$(date +%H:%M)
echo "Current time (without seconds): $time_without_seconds"

with_Am_Pm=$(date +%r)
echo "Current time (12-hour format): $with_Am_Pm"

current_hours=$(date +%H)
echo "Current hours: $current_hours"
EXPLANATION

The script starts with the shebang (#! /bin/bash) that specifies the Bash interpreter. The date command obtains the current date and assigns it to the today variable. It then echoes the message “Today’s date: ” followed by the value of today, which represents the current date.

Next, the script retrieves the current time in seconds by using the date command with the format specifier %T. Furthermore, the script retrieves the current time without seconds using the format specifier %H:%M.

Afterward, the script prints the current time in a 12-hour format with AM/PM designation by using the format specifier %r.

Lastly, the script obtains the current hour using the format specifier %H and assigns it to the current_hours variable. It echoes the message “Current hours: ” followed by the value of current_hours, representing the current hour in 24-hour format.

❹ Use the following command to make the file executable:

chmod u+x time.sh
EXPLANATION
  • chmod: Changes permissions.
  • u+x: Giving the owner executing permission.
  • time.sh: Name of the script.
Changing file permission to print time in Bash❺ Run the script by the following command:
./time.sh

How to print time in Bash in different format The date command prints the current date as ‘Wed Jun 21 12:46:35 PM +06 2023’. Later it prints only the current time with seconds which is 12:46:35. Furthermore, the program prints the current time without seconds which is 12:46. Lastly, it prints the current hour only, using the format specifier +%H.

Useful Format Specifiers for Printing Time in Bash Script

Some useful format specifiers for printing time are listed below:

Format Description Example code Sample Output
%H Hour in 24-hour format $ date +%H 23
%I Hour in 12-hour format $ date +%I 12
%M Print minutes of current hour $ date +%M 46
%s Print seconds of the current minute $ date +%s 35
%z +hhmm numeric time zone $ date +%z +0600
%:z +hh:mm numeric time zone $ date +%:z +06:00
%::z +hh:mm:ss numeric time zone $ date +%::z +06:00:00
%:::z numeric time zone with : to necessary precision(+06, -05:30) $ date +%:::z +06
%p AM/PM designation

Method 2: Printing Time Using the “timedatectl” Command

The timedatectl command is useful to configure the system’s date and time settings. But one can creatively use this command to get the system’s time. Follow the script below to visualize this.

You can follow the Steps of Method 01 to learn about creating and saving shell scripts.

Scripts (timectl.sh) >

#!bin/bash

time=timedatectl | awk '/Local time:/ {print $5}'
echo $time
EXPLANATION

The given Bash script captures the local time by executing the timedatectl command and extracting the fifth field from the line containing “Local time:” using the awk command. The extracted time value is assigned to the time variable using command substitution. Finally, the script displays the value stored in time using the echo command.

Run the script by the following command:

./timectl.sh

printing time using timectl commandWhile running the program it shows the current time as the image shows above. By default, this time is in a 24-hour time format.

Comparative Analysis of Methods

Here is a comparative analysis between the above-discussed methods. You can look at the pros and cons of each method to determine the best one for you.

Method Pros Cons
date command
  • Designed for displaying time and date.
  • Huge number of formatting options.
  • May have limitations when working with dates outside a certain range.
timedatectl command
  • Display many other information about the system along with time.
  • Have to extract time from other information using command rather than datetimectl.
  • Limited formatting options.

I personally favor using the date command over timedatectl when it comes to printing time. In case of timedatectl, you have to extract the date field from the information it returns, which adds complexity. However, the date command is more straightforward for displaying time, eliminating the need for additional commands.

How to Get the Run Time Using the “time” Command in Bash

The time command in Bash allows you to measure the execution time of a given command or script. When you prefix a script with the time command, it gives you the different system time of the script.

You can follow the Steps of Method 01 to learn about creating and saving shell scripts.

Scripts (binary.sh) >

#!/bin/bash

echo "Enter a number:"
read n
val=0
power=1

while [ $n -ne 0 ]
do
r=$(( $n % 2 ))
val=$(( $r * $power + $val ))
power=$(( $power * 10 ))
n=$(( $n / 2 ))
done

echo "Binary output: $val"
EXPLANATION

The provided Bash script prompts the user to enter a number, reads the input and then converts the number to its binary representation using a loop. Inside the loop, it calculates the remainder of the number divided by 2, which represents the least significant bit of the binary representation.

It then accumulates this bit in the val variable by multiplying it with the current position value (power) and adding it to the accumulated value. The position value is updated by multiplying it by 10 to move to the next position in the binary representation. The number is divided by 2 to shift it to the right in the binary representation. The process continues until the number becomes zero. Finally, it displays the resulting binary representation stored in the val variable.

Run the script by the following command:

./convert_binary.sh

Binary representation of numberThe script provided can convert a decimal number into its binary representation. In this case, the script takes the input value of 4 and successfully converts it into its binary equivalent.DIfferent system timeThis time I run the script by adding the time command as a prefix. You can see that the given input is again 4 and it successfully converts the number into its binary representation. Moreover, it shows three different times namely real, user, and sys time.

The real time also known as the wall clock time represents the actual elapsed time from the start of the script until its completion. The real-time of the script is 3.776s. Then comes the user time which refers to the amount of CPU time consumed in user-mode by the executed script. The user time of the executed script is .002s. Lastly, the sys time represents the amount of CPU time consumed in the kernel mode by the convert_binary.sh script while execution.

Conclusion

In conclusion, printing the local time or CST time is easier with the date command. On the other hand, one can use the time command to print system time. I believe with the knowledge of the above discussion, you can now print the local time in your machine as well as the system time of a Bash script.

People Also Ask

How to print time in terminal

To print time in the terminal of Linux or any Unix operating system, you must go to the terminal and type the date command with the necessary formatting.

How to get currenct time up to milliseconds in Bash
Use +%H:%M:%S:%3N format specifier with date command to print current time up to milliseconds.
How to print timestamp in Bash
To print timestamp in Bash use the date command with the necessary format specifier.

Related Articles


<< Go Back to Bash Script Examples | Bash Scripting Basics | Bash Scripting Tutorial

Rate this post
Md Zahidul Islam Laku

Hey, I'm Zahidul Islam Laku currently working as a Linux Content Developer Executive at SOFTEKO. I completed my graduation from Bangladesh University of Engineering and Technology (BUET). I write articles on a variety of tech topics including Linux. Learning and writing on Linux is nothing but fun as it gives me more power on my machine. What can be more efficient than interacting with the Operating System without Graphical User Interface! Read Full Bio

Leave a Comment