How to Get Current Time in Bash [4 Practical Cases]

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

The date command in Bash is used to get the current time. The current time may differ depending on which current time it refers to. For example, someone may want the local current time, others may want the UTC time irrespective of timezone. Moreover one may be interested in the component of current time let’s say the current hour or minute. This article walks you through the use of the date command to get the time details you need.

Key Takeaways

  • Printing current time in different formats.
  • Getting UTC time using date command.
  • Printing Unix time and converting it to UTC.

Free Downloads

4 Cases of Printing Current Time in Bash

Getting current time can be different based on the necessity of the user. One can print the current time in many ways using different format specifiers and options of date command. Now I am going to discuss four different cases of getting current time.

Case 1: Getting Current Time in “HH:MM:SS (12 Hour)” Format

To get the current time in HH:MM:SS format use %r format specifier in the date command. %T format specifier also works well however it will print time in 24-hour format. Now, I am going to print time in 12-hour format using %r.

Steps to Follow >

❶ At first, launch an Ubuntu Terminal.

❷ Write the following command to open a file named currtime.sh in the build-in nano editor:

nano currtime.sh
EXPLANATION
  • nano: Opens a file in the Nano text editor.
  • currtime.sh: Name of the file.
Creating a Bash script file in nano❸ Copy the following scripts and paste them into nano. Press CTRL+O and ENTER to save the file; CTRL+X to exit. Alternatively, copy the following script. Paste the script into a text editor and save it as .sh file.

Script (currtime.sh) >

#!/bin/bash

echo "Current time: $(date +"%r")"
EXPLANATION

The date command with the format specifier %r, retrieves  time in a 12-hour format with AM/PM indicators. The echo command is used to display the time.

❹ Use the following two commands to make the file executable:

chmod u+x currtime.sh
EXPLANATION
  • chmod: Changes permissions.
  • u+x: Giving the owner executing permission.
  • currtime.sh: Name of the script.

Changing permission of the Bash script file❺ Run the currtime.sh script by the following command:

./currtime.sh

Printing current time in 12-hour formatOnce executed the echo command prints the current time in 12-hour format with AM/ PM as shown in the image above.

Case 2: Getting Component of Current Time Using Bash Script

If you are interested only in a component of current time then you can use format specifiers like %I, %M, %S and %3N. For example, %I is used to get the current hour in a 12-hour format. %M  is used to get the running minute of the current hour. %S is used to print current seconds and %3N can be used to print the second up to 3 decimal points precision. Look at the implementation of these in the Bash script below:

You can follow the Steps of Case 1 to learn about creating and saving shell scripts.

Script (component.sh) >

#!/bin/bash

current_hour=$(date +"%I")
current_minute=$(date +"%M")
current_second=$(date +"%S")
current_millisecond=$(date +"%3N")

echo "Current Hour: $current_hour"
echo "Current Minute: $current_minute"
echo "Current Second: $current_second"
echo "Current Millisecond: $current_millisecond"
EXPLANATION

This Bash script captures the current hour, minute, second and millisecond from the system’s time using the date command. It prints out each of these components separately using the echo command. The script retrieves the hour in 12-hour format (%I), the minute (%M), the second (%S) and milliseconds (%3N) and displays them as individual pieces of information.

Run the component.sh script by the following command:

./component.sh

Printing component of current timeAs you can see the %I retrieve the current hour in a 12-hour format which is 2. %M  retrieve the running minute(0 to 59) which is 57. Finally, %S and %3N are used to get the current second (0 to 59) and milliseconds (0 to 999) which are 44 and 859 respectively.

Case 3: Getting UTC Time Using Bash

UTC or Coordinated Universal Time is a time which is the same worldwide regardless of timezones. This time is important and used in many fields. The -u option of date command can effectively retrieve the current UTC time.

You can follow the Steps of Case 1 to learn about creating and saving shell scripts.

Script (utctime.sh) >

#!/bin/bash

current_utc_time=$(date -u +"%H:%M:%S %Z")
echo "Current UTC Time: $current_utc_time"
EXPLANATION

This Bash script obtains the current Coordinated Universal Time (UTC) by using the date command with the -u option, which indicates that the output should be in UTC.
The format specifier %H represents the hour, %M the minute, %S the second and %Z the time zone abbreviation. The script then echoes the current UTC time in [hh:mm:ss] [UTC] format.

Run the utctime.sh script by the following command:

./utctime.sh

Getting current UTC timeOnce executed the program successfully prints the current UTC time which is 09:04:46 UTC in case of the above execution.

Case 4: Printing Current Unix Time

Unix time or POSIX time is a way of tracking time. It represents the number of seconds that have elapsed since the Linux epoch- a specific point in time defined as 00:00:00 UTC on January 1, 1970. %s specifier is used to retrieve the current Unix time.

You can follow the Steps of Case 1 to learn about creating and saving shell scripts.

Script (currunix.sh) >

#!/bin/bash

current_unix_time=$(date +%s)
echo "Current Unix Time: $current_unix_time"
EXPLANATION

The date command with %s format specifier captures the Unix time and assigns it to the current_unix_time variable.

The echo command is used to display the current Unix time with necessary messages.

Run the currunix.sh script by the following command:

./currunix.sh

Getting current Unix timeOnce executed the script will print the current Unix time. In the above execution it prints  1692781661 as the running Unix time.

How to Get Current Time Using timedatectl Command

The timedatectl command extracts information about the time and date settings of the system. From the extracted information one can easily find out the local time, UTC time etc using the awk command.

You can follow the Steps of Case 1 to learn about creating and saving shell scripts.

Script (timedatectl.sh) >

#!bin/bash

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

The script first employs timedatectl to fetch information about the system’s date and time settings. Through the use of the awk command it targets the line containing “Local time“. The fifth field (column) of the targeted line corresponds to the local time value. {print $5} is used to store the extracted value within the curr_time variable. Finally, the echo command is utilized to print the value of curr_time.

Run the timedatectl.sh script by the following command:

./timedatectl.sh

Printing current time using timedatectl commandAs you can see, the current time 15:24:37 is printed in 24-hour format.

How to Convert UTC Unix Time to a Specific Timezone Using Bash Script

Let’s say you have a Unix time. Now you want to convert this into human readable UTC time. -d option of date command is useful for this purpose. The below script is designed to convert a given Unix timestamp into UTC time of a specified timezone using the -d option.

You can follow the Steps of Case 1 to learn about creating and saving shell scripts.

Script (converttime.sh) >

#!/bin/bash

utc_unix_time=1665248424
timezone="America/New_York"

echo "Unix time: $utc_unix_time"
converted_time=$(TZ=$timezone date -u -d "@$utc_unix_time" +"%Y-%m-%d %H:%M:%S %Z")
echo "Converted Time: $converted_time"
EXPLANATION

The utc_unix_time variable has a value of 1665248424, which is actually a Unix timestamp. The timezone variable is set to America/New_York. The TZ environment variable is temporarily set to the specified timezone. The date command is used with the -u option to indicate the input is in UTC. The -d option is utilized to convert the UTC Unix timestamp into the desired timezone.

The output format is defined using the format specifier %Y-%m-%d %H:%M:%S %Z, which represents year, month, day, hour, minute, second, and timezone abbreviation respectively.

Run the converttime.sh script by the following command:

./converttime.sh

Converting Unix time to UTC timeRunning the script will output the original Unix time and the corresponding UTC time in the designated time zone. As you can see Unix time 1665248424 is actually referring to 2022-06-08 13:07:04 UTC time.

Conclusion

In conclusion, getting the current time in Bash is important and useful. Maintaining a log, scheduling a specific task and keeping track of recent backups are inherently related to current time of various forms. I believe after reading this article, you will be nothing if not a pro in handling time-related issues in Bash.

People Also Ask

How to get precision in seconds up to a specific decimal point?
To get a precision in seconds up to certain decimal point use %N format specifier. For example, %3N will print seconds up to three decimal points.
Is time command used to get the current time in Bash?
No. time command is used to see different time related info about the execution of a Bash script.   
Is there any other way to get the current Unix time except date command?
Yes, you can use the Python time module to get the current Unix time if you don’t want to use the date command. python -c ‘import time; print(int(time.time()))’ command will successfully print the current Unix time in the terminal.

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