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.
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.
❶ 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
- nano: Opens a file in the Nano text editor.
- time.sh: Name of the 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"
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
- chmod: Changes permissions.
- u+x: Giving the owner executing permission.
- time.sh: Name of the script.
./time.sh
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.
Scripts (timectl.sh) >
#!bin/bash
time=timedatectl | awk '/Local time:/ {print $5}'
echo $time
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
While 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 |
|
|
timedatectl command |
|
|
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.
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"
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
The 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.
This 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
Related Articles
- How to Get Date in Bash [2 Methods with Examples]
- How to List Users in Bash [2 Easy Ways]
- How to Get Current Time in Bash [4 Practical Cases]
- How to Use Date Format in Bash [5 Examples]
- How to Get Timestamp in Bash [2 Practical Cases]
- How to Copy and Paste in Bash [2 Methods & Cases]
- How to Read Password in Bash [3 Practical Cases]
- How to Send Email in Bash [2 Easy Methods]
- Bash Script to Send Email with Attachment [Step-by-Step Guide]
- How to Get IP Address in Bash [3 Methods]
- How to Find and Replace String in Bash [5 Methods]
- How to Get Script Name Using Bash Script? [3 Easy Ways]
- How to Call Another Script in Bash [2 Methods]
- How to Generate UUID in Bash [3 Simple Methods]
- 3 Easy Ways to Write to a File in Bash Script
- How to Write the Output to a File in Bash Script [5 Practical Cases]
- How to Create a List in Bash Scripts? [2 Easy Methods]
- How to Clear History in Bash [2 Practical Cases]
- How to Clear Screen Using Bash Script? [2 Effective Methods]
- How to Check Ubuntu Version Using Bash Scripts? [2 Methods]
<< Go Back to Bash Script Examples | Bash Scripting Basics | Bash Scripting Tutorial