Tuesday, May 24, 2016

How to Get Current Time In Shell Script ?


How do I get the current server time in shell script on Linux or Unix-like operating systems? 
How do I store the current time in the shell variable and use in my scripts?

You can use the date command to display or set the current date and time. You need to use the date FORMAT syntax to controls the output of the date command. The %T format sequence interpreted by the date command to display the current time. The syntax is:


date +%FORMAT
date +"%FORMAT"
var=$(date +"%FORMAT")

Example: Show current time

Open a terminal and type the following command:
date +"%T"
Sample outputs:
13:24:21
To store time to a shell variable called now, enter:
now=$(date +"%T")
echo "Current time : $now"
Sample outputs:
Current time : 13:24:21
date +%FORMAT
date +"%FORMAT"
var=$(date +"%FORMAT")

Example: Show current time

Open a terminal and type the following command:
date +"%T"
Sample outputs:
16:33:22
To store time to a shell variable called now, enter:
now=$(date +"%T")
echo "Current time : $now"
Sample outputs:
Current time : 13:31:55

Example: 12 hour clock time

Pass the %r format to the date command:
date +”%r”
Sample outputs:
”12:25:43 PM”
To remove AM or PM from the output use, type:
date +"%I:%M:%S"
Sample outputs:
12:26:27


No comments:

Post a Comment