Unix & Linux: How to append date to backup file? (9 Solutions!!)

preview_player
Показать описание
Unix & Linux: How to append date to backup file?

The Question: I need to make a backup of a file, and I would like to have a timestamp as part
of the name to make it easier to differentiate.
How would you inject the current date into a copy command?
cp: target `2013}' is not a directory

cp: target `}' is not a directory

cp: target `2013' is not a directory

Solutions: Please watch the whole video to see all solutions, in order of how many people found them helpful

== This solution helped 4 people ==
As date has by default whitespaces in its output, your last command failed. If
you had quoted the last argument inside with ", it should work. Your other
tries have just wrong syntax
Here a possible solution without whitespaces:
or
If you add
bk() {
cp -a "$1" "${1}_$(date --iso-8601=seconds)"
}
to your .bashrc and re-login/let your bash reread it, you need just to call bk

== This solution helped 11 people ==
If you really want to use the verbose date, you should protect the backtick.
The with this date format is that it has embedded spaces, a no-no in a Unix
shell unless you put them inside quotes (or escape them some other way).
However, I prefer to use the shorter ISO format:

== This solution helped 113 people ==
This isn't working because the command date returns a string with spaces in it.
$ date
Wed Oct 16 19:20:51 EDT 2013
If you truly want filenames like that you'll need to wrap that string in
quotes.

$ ll foo*
You're probably thinking of a different string to be appended would be my guess
though. I usually use something like this:
$ ll foo*
output for the date & time.
**** Additional formats ****
If you want to take full control if you consult the man page you can do things
like this:
$ date +"%Y%m%d"
20131016

$ date +"%Y-%m-%d"
2013-10-16

$ date +"%Y%m%d_%H%M%S"
20131016_193655
NOTE: You can use date -I or date --iso-8601 which will produce identical
output to date +"%Y-%m-%d. This switch also has the ability to take an https://
$ date -I=?
date: invalid argument '=?' for '--iso-8601'
Valid arguments are:
- 'hours'
- 'minutes'
- 'date'
- 'seconds'
- 'ns'
Try 'date --help' for more information.
Examples:
$ date -Ihours
2019-10-25T01+0000

$ date -Iminutes
2019-10-25T01:21+0000

$ date -Iseconds
2019-10-25T01:21:33+0000

== This solution helped 5 people ==
Use a function, it will make your life easier. This is what I use:
backup () {
for file in "$@"; do
local new=${file}.$(date '+%Y%m%d')
while [[ -f $new ]]; do
new+="~";
done;
printf "copying '%s' to '%s'n" "$file" "$new";
cp -ip "$file" "$new";
done
}

Рекомендации по теме
Комментарии
Автор

This video saved my lot of time. Thank you

muralik
visit shbcf.ru