When I started writing bash scripts, I realized that one operation I am often dealing with every script is handling date and time. I have done many operations like naming a file/directory with date, fetching API result, and transforming the epoch value to date/time suitable for the application, manipulating date column in CSV files, etc. If you are a beginner for Bash scripting, this article will help in understanding how to use date command in Bash scripting, how to work with date and time using date command in shell scripts, how to manipulate them and do various operations with it in Linux.
You should have a basic understanding of how a system date and time is set. This part will mostly be taken care of by the server admin in your work.
But if you are an individual user and using Linux in your personal machine, then you should have an understanding of how date and time are set, ways to synchronize them, and how to modify it.
There are two clocks used by Linux to keep the time sync.
- Real-Time Clock - This is a clock integrated into your system motherboard and will run even if you shut down the machine.
- System Clock - This will be handled by the Linux kernel and during the system boot kernel will get the initial time from the real-time clock.
I am not going to go through the process of setting up a date and time, that’s a separate topic to discuss. Let’s start looking into the core part of this article on how to use the date
command in Bash scripting in Linux.
Table of Contents
Getting Help
First, you can check the binary location of the date
command by running the following command.
$ which date /usr/bin/date
The date
command is not a shell builtin but an external program. You can get that information by running the type
command.
$ type -a date date is /usr/bin/date date is /bin/date
There are many options to work with and remembering everything is not possible and this is where the help and man page will come in handy.
Run the following command to access the man page of date
command.
$ man date
Run the following command to access the help message.
$ date --help
Print Current Date And Time
Launch your terminal and simply run the date
command. You will get the current date along with the time and timezone. In my case, I have set the timezone as IST during my OS installation.
$ date Sunday 13 February 2022 11:27:17 AM IST
You can also get the date and time in the UTC timezone by using the -u
flag.
$ date -u Sunday 13 February 2022 05:57:36 AM UTC
TimeZone Conversion
You can get the output of the date
command in different timezones by setting the environmental variable TZ. I have set the TZ to Moscow and Singapore time zone in the below example.
$ Z="Europe/Moscow" date
Sunday 13 February 2022 08:59:03 AM MSK
$ TZ="Asia/Singapore" date
Sunday 13 February 2022 01:59:37 PM +08
You can get the list of timezones by running the "timedatectl
" command.
$ timedatectl list-timezones
$ timedatectl list-timezones | grep -i singapore
Asia/Singapore
Singapore
$ timedatectl list-timezones | grep -i moscow
Europe/Moscow
Last Modified Time Of A File
Normally, we use the stat
command to check the modified time of a file. The same can be checked with the date
command using the -r
flag.
$ stat ~/.bashrc File: /home/karthick/.bashrc Size: 4342 Blocks: 16 IO Block: 4096 regular file Device: 806h/2054d Inode: 27787278 Links: 1 Access: (0644/-rw-r--r--) Uid: ( 1000/karthick) Gid: ( 1000/karthick) Access: 2022-02-13 09:06:45.713721080 +0530 Modify: 2022-02-11 20:18:52.485178931 +0530 Change: 2022-02-11 20:18:52.485178931 +0530 Birth: -
$ date -r ~/.bashrc Friday 11 February 2022 08:18:52 PM IST
You can see the stat
command output format is different from the date
command, but both serve the same purpose.
Different Formatting Options
The date
command supports formatting options and using these options you can format your date
command output to be in any format you desire or you can grab only the particular value from the output.
Open the date
command's man page and look for the section as shown in the below image.
There are a lot of formatting options, but not all will be useful. We will see some of the important formatting options and understand how it works.
By default, the date
command will display the date and time. What if you wish to print only the date or time?
$ date
Sunday 13 February 2022 11:27:17 AM IST
To get only the date, you can use the %F
flag or %D
flag.
$ date +%F
2021-11-16
$ date +%D
02/13/22
When you are using formatter flags, you should prefix it with +
symbol as I did in the above examples.
- The output from the
%F
flag will be in YYYY-MM-DD format. - The output from the
%D
flag will be in MM/DD/YY format.
You can grab the day, month, and year individually and create your own new formatted output.
$ date +%Y
2022
$ date +%m
02
$ date +%d
13
To create your own formatted output, just combine all the flags a shown below.
$ date +%Y_%m_%d
2022_02_13
Similar to date, you can also get the time alone using %r
(12 hour format) or %T
(24 hour format) flags.
$ date +%r # 12 hour format
11:24:12 PM IST
$ date +%T # 24 hour format
23:24:11
You can grab hours, minutes, seconds individually and create your own formatted output.
$ date +%H
12
$ date +%M
24
$ date +%S
03
Combine all the above flags and create custom output.
$ date +%H_%M_%S
12_26_53
Now where do these custom formatting options help? For me, when I create any files as part of the script, I will name it with today’s date. So It will be useful for me to take a look at it when needed.
Till now we have seen how to work with date and time individually. Sometimes, you may want to display both date and time. In that case, you can combine the date and time like below or create your own formatted output.
$ date "+%F %r"
2021-11-16 11:29:06 PM IST
Run Script Only On Certain Days
In some cases, you may want to run your script only on a certain day of the week. For example, if I want my script to run only on Friday, then I can use %A
(Friday) or %a
(Fri) flags and write logic accordingly.
if [[ $(date +%A) = Friday ]] then echo "Running the code" else echo "Today is not Friday, Exiting the script" fi OUTPUT: Today is not Friday, Exiting the script
There are more formatting options available. Refer to the man page and explore them all.
Storing Output To A Variable
When writing scripts it is a best practice to store the output of the date
command to a variable and use the variable in the script. One such scenario will be creating the file name with the date and time.
Take a look at the below example where today's date will be stored in variable TDY
and the same is used to create a file name "disk_usage_${TDY}.txt
" which will store the output of the "df -h
" command.
$ TDY=$(date +%F)
$ df -h > ~/disk_usage_${TDY}.txt
$ ls -l *.txt -rw-rw-r-- 1 karthick karthick 474 Feb 13 23:40 disk_usage_2022-02-13.txt
$ cat disk_usage_2022-02-13.txt Filesystem Size Used Avail Use% Mounted on tmpfs 1.6G 154M 1.5G 10% /run /dev/sda7 93G 27G 61G 31% / tmpfs 7.8G 82M 7.7G 2% /dev/shm tmpfs 5.0M 0 5.0M 0% /run/lock tmpfs 4.0M 0 4.0M 0% /sys/fs/cgroup /dev/sda9 261G 130G 118G 53% /nextdrive /dev/sda6 348G 110G 221G 34% /home /dev/sda5 2.0G 234M 1.8G 12% /boot/efi tmpfs 1.6G 180K 1.6G 1% /run/user/1000
Using -d
or --date
Flag
This is an important feature I like the most with the date
command. You can pass the string as an argument to -d
or --date
flag and you will get the output in the default format.
Take a look at the below examples. I have passed string arguments as "today
", "yesterday
", "tomorrow
", "last Thursday
", "Today (+,-) 20 years
" to the --date
flag. Date command will interpret these strings and convert the output to its default format.
$ date --date "Today"
Sunday 13 February 2022 01:01:26 PM IST
$ date --date "now"
Sunday 13 February 2022 01:01:34 PM IST
$ date --date "yesterday"
Saturday 12 February 2022 01:01:39 PM IST
$ date --date "Tomorrow"
Monday 14 February 2022 01:01:45 PM IST
$ date --date "Last Thursday"
Thursday 10 February 2022 12:00:00 AM IST
$ date --date "Today - 20 years"
Wednesday 13 February 2002 01:01:56 PM IST
$ date --date "Today + 20 years"
Thursday 13 February 2042 01:02:01 PM IST
You can pass more relative string arguments other than what I have shown in the above example.
Epoch Time
Epoch time can be converted to the current date and time format using the -d
or --date
flag. The %s
flag output will be in epoch format.
$ date +%s
1644737777
To convert it to standard human-readable format, add @
followed by epoch time like as shown below.
$ date --date @1644737777
Sunday 13 February 2022 01:06:17 PM IST
In all the above examples, you can see the default output is displayed. You can combine the formatters along with the -d
or --date
flag to get custom output.
$ date --date "Today + 20 years" +%Y
2042
$ date --date "Today + 21 years" +%s
2275890194
$ date --date @2275890194 +%Y
2042
Conclusion
In this article, we discussed how to use the date
command in Bash scripting with examples. By this time, you should be comfortable in using the date
command in your scripts. There are a lot of formatting options available, test and get familiar with them.
If you have any feedback or suggestions about this article, let us know via the comment section below.
Bash scripting guides:
- How To Debug Bash Scripts In Linux And Unix
- Bash Scripting – Parse Arguments In Bash Scripts Using getopts
- How To Create GUI Dialog Boxes In Bash Scripts With Zenity In Linux And Unix
- Bash Scripting – Case Statement
- Bash Scripting – Conditional Statements
- Bash Scripting – String Manipulation
- Bash Scripting – Printf Command Explained With Examples
- Bash Scripting – Indexed Array Explained With Examples
- Bash Scripting – Associative Array Explained With Examples
- Bash Scripting – For Loop Explained With Examples
- Bash Scripting – While And Until Loop Explained With Examples
- Bash Redirection Explained With Examples
- Bash Scripting – Variables Explained With Examples
- Bash Scripting – Functions Explained With Examples
- Bash Echo Command Explained With Examples In Linux
- Bash Heredoc Tutorial For Beginners
1 comment
As well as %F and %D for date only, there is %x. Most people will want %x rather than %D as it uses their locale setting instead of being in the fixed USA format. E.g. I’m in the UK and %x gives me DD/MM/YY. Likewise for date and time, most people would want either %c or “%x %X” or “%x %r” for fully localised output, or something like “%F %T” for fixed-format output. Using “%F %r” would be a weird thing to do as it is part fixed format (%F) and part localised (%r).