Bijan Bijan - 4 months ago 10
Bash Question

Shell Script: Copy Multiple Files and add Timestamp

I have a folder that contains a few

.db
files and I am trying to create a shell script that copies every
*.db
file but adds the current date to the file

For example, the folder contains
A.db
,
B.db
,
C.db
. I want it to copy
A.db
to
/Backups/A_2016_07_21.db
and so on.

I know I can do
cp -a A.db /Backups/A.db
but I am looking for a more automated way to do it for every
*.db
file and also add the current date

Answer

Iterate over the files using a for construct and cp files to the destination with getting desired file names using bash parameter expansion and date:

for f in *.db; do cp -a "$f" /Backups/""${f%.db}"_$(date '+%Y_%m_%d').db"; done
Comments