Rippo
Rippo

Reputation: 22424

prepend date to a filename in a shell script

I have the following shell script and want to change the filename db_backup.sql to be change so the current date is prepended to it e.g. yyyy-mm-dd-db_backup.sql

#!/bin/sh
mysqldump ... /_sql/db_backup.sql
gzip -f _sql/db_backup.sql

Simple question, hopefully quick and simple answer!

Upvotes: 0

Views: 1046

Answers (2)

paxdiablo
paxdiablo

Reputation: 882776

You can use the date command to do what you want:

#!/bin/sh
fspec=/_sql/$(date +%Y-%m-%d)-db_backup.sql
mysqldump ... ${fspec}
gzip -f ${fspec}

If you're using a shell that doesn't support $(), you may need to use backticks instead:

fspec=/_sql/`date +%Y-%m-%d`-db_backup.sql

Upvotes: 6

krico
krico

Reputation: 5728

use POSIX qw(strftime);
my $file = sprintf("%s-db_backup.sql",  strftime "%Y-%m-%d", localtime);

Upvotes: 0

Related Questions