≡ Menu

How to append current date to a file name on Linux?

The question is – I am creating a backup bash shell script using tar and gz and I need to automatically append the current date and time to the file name. Is there a Linux command that can be used to do this?

The Linux command that can get the current date and time is called date. When used without arguments, the date command outputs the current date and time.

[root@server ~]# date
Fri Sep 6 15:11:37 MSD 2013

To get the current date and time to append to a file name, the following format is more useful:

[root@server ~]# date +"%m_%d_%Y_%H_%M"

The format string is explained below:

%m – month
%d – date
%Y – year
%H – hour (24 hour clock)
%M – minute

Now to append this string to a file name, you can use the following bash script:

now_var=`date +%m_%d_%Y_%H_%M`
#echo $now_var
echo "Creating new file $file_var..."
tar -cvf $file_var *.*
gzip $file_var

(Note here that in the second line in which now_var is being created, the symbol after = is ` (the key on the left side of the number 1 on a standard keyboard) and its not a single quote!).

The above shell script will create a file like backup.09_06_2013_15_29.tar.gz in the current directory with all files in the current directory and all sub-directories tar’d and gzip’d into that file!

Comments on this entry are closed.