Reputation: 37
I am planning to write an SSH script to backup my database file. I want the file name auto-assign as db_{date}{hour}.sql (exact format: db_MMDDYYYYhhmm.sql
) based on the timestamp when I run the script. How can I do that? Thank you.
Upvotes: 2
Views: 1719
Reputation: 1276
Assuming my filename is named
/tmp/file
I can get the full timestamp of an existing file by using
ls --ful-time /tmp/file
For example, I created a test file by running
touch /tmp/file`
Now I get the timestamp of it by running
[jishak@hostname /]$ ls --full-time /tmp/file
-rw-rw---- 1 jishak psi 0 2021-02-24 14:27:11.210013175 -0800 /tmp/file
To rename the file to match the timestamp of the file, I can use the below bash script to get the timestamp from the file and rename the file to match it using your format. This doesn't necessarily help you with new files but can help you after you have created the backup as well as to rename older backups that you want in the new format.
#!/bin/bash
#replace your filename in the backticks below. I am using touch to create an empty file for this example
export filename=`touch /tmp/file`
#get the year from the timestamp of the file (ie 2021)
export fileyear=`ls --full-time ${filename} | awk '{ print $6 }' | cut -c 1-4`
#get the month as 2 digits for sorting purposes (ie Feb to 02)
export filemonth=`ls --full-time ${filename} | awk '{ print $6 }' | cut -c 6-7`
#get the date of the month from the timestamp of the file (ie 24th is 24)
export filedate=`ls --full-time ${filename} | awk '{ print $6 }' | cut -c 9-10`
#get the 2 digit hour from the timestamp of the file (ie 14)
export filehour=`ls --full-time ${filename} | awk '{ print $7 }' | cut -c "1,2"`
#get the 2 digit minute from the timestamp of the file (ie 27)
export filemin=`ls --full-time ${filename} | awk '{ print $7 }' | cut -c "4,5"`
#finally rename the file to the new format
mv ${filename} db_${filemonth}${filedate}${fileyear}${filehour}${filemin}.sql
*Note this was tested on Centos 7 as that is what I am runnig.
Upvotes: 0
Reputation: 6134
If you are using Bash (/bin/bash
), this will put the name of the file into the variable file_name
:
$ printf -v file_name 'db_%(%m%d%Y%H%M)T.sql' -2
$ echo "File name is: '$file_name'"
File name is: 'db_022420212146.sql'
You can do this at any time in your script since -2
is a special value representing the time Bash started, i.e. when your script was run.
If you are using a POSIX shell (/bin/sh
), then you must add this at the beginning of your script:
file_name=$(date +db_%m%d%Y%H%M.sql)
(of course this would work with Bash too)
Upvotes: 3