ycliper

Популярное

Музыка Кино и Анимация Автомобили Животные Спорт Путешествия Игры Юмор

Интересные видео

2025 Сериалы Трейлеры Новости Как сделать Видеоуроки Diy своими руками

Топ запросов

смотреть а4 schoolboy runaway турецкий сериал смотреть мультфильмы эдисон
Скачать

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

Автор: Роэль Ван де Паар (Техническая помощь Роэля)

Загружено: 2020-08-07

Просмотров: 146

Описание: 👉 https://amzn.to/4aLHbLD 👈 You’re literally one click away from a better setup — grab it now! 🚀👑

As an Amazon Associate I earn from qualifying purchases. 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?
[root@mongo-test3 ~]# cp foo.txt {,.backup.`date`}
cp: target `2013}' is not a directory

[root@mongo-test3 ~]# cp foo.txt {,.backup. $((date)) }
cp: target `}' is not a directory

[root@mongo-test3 ~]# cp foo.txt foo.backup.`date`
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:
cp foo.txt foo.backup.$(date --iso-8601=seconds)
or
cp foo.txt foo.backup.`date --iso-8601=seconds`
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
file.txt.

== 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).
cp foo.txt "foo-`date`.txt"
However, I prefer to use the shorter ISO format:
cp foo.txt foo-`date --iso`.txt

== 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.
$ touch "foo.backup.$(date)"

$ ll foo*
rw-rw-r- 1 saml saml 0 Oct 16 19:22 foo.backup.Wed Oct 16 19:22:29 EDT 2013
You're probably thinking of a different string to be appended would be my guess
though. I usually use something like this:
$ touch "foo.backup.$(date +%F_%R)"
$ ll foo*
rw-rw-r- 1 saml saml 0 Oct 16 19:25 foo.backup.2013-10-16_19:25
See the http://linux.die.net/man/1/date for more formatting codes around the
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://
unix.stackexchange.com/questions/164826/date-command-iso-8601-option:
$ 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
}

With thanks & praise to God, and with thanks to the many people who have made this project possible! | Content (except music & images) licensed under cc by-sa 3.0 | Music: https://www.bensound.com/royalty-free... | Images: https://stocksnap.io/license & others | With thanks to user user1338062 (https://unix.stackexchange.com/users/..., user Steve Rowe (https://unix.stackexchange.com/users/..., user spuder (https://unix.stackexchange.com/users/..., user slm (https://unix.stackexchange.com/users/..., user Railgun2 (https://unix.stackexchange.com/users/..., user jofel (https://unix.stackexchange.com/users/..., user glenn jackman (https://unix.stackexchange.com/users/..., user Gilles 'SO- stop being evil' (https://unix.stackexchange.com/users/..., user fernando garza (https://unix.stackexchange.com/users/..., user Atul Rokade (https://unix.stackexchange.com/users/..., and the Stack Exchange Network (http://unix.stackexchange.com/questio.... Trademarks are property of their respective owners. Disclaimer: All information is provided "AS IS" without warranty of any kind. You are responsible for your own actions. Please contact me if anything is amiss at Roel D.OT VandePaar A.T gmail.com.

Не удается загрузить Youtube-плеер. Проверьте блокировку Youtube в вашей сети.
Повторяем попытку...
Unix & Linux: How to append date to backup file? (9 Solutions!!)

Поделиться в:

Доступные форматы для скачивания:

Скачать видео

  • Информация по загрузке:

Скачать аудио

Похожие видео

Как Ubuntu Предала Linux - Вся Правда о Взлёте и Падении Canonical

Как Ubuntu Предала Linux - Вся Правда о Взлёте и Падении Canonical

ВСЕ ЧТО НУЖНО ЗНАТЬ ПРО LINUX

ВСЕ ЧТО НУЖНО ЗНАТЬ ПРО LINUX

Linked List From Scratch in C | Pointers, Memory & Insert/Delete Explained

Linked List From Scratch in C | Pointers, Memory & Insert/Delete Explained

Unix & Linux: How to detect an error using process substitution? (3 Solutions!!)

Unix & Linux: How to detect an error using process substitution? (3 Solutions!!)

Unix & Linux: How to switch between users on one terminal? (9 Solutions!!)

Unix & Linux: How to switch between users on one terminal? (9 Solutions!!)

Unix & Linux: Unable to get graphics to work on a Fedora 17 on a Intel Atom board (2 Solutions!!)

Unix & Linux: Unable to get graphics to work on a Fedora 17 on a Intel Atom board (2 Solutions!!)

Как Windows работает с ОЗУ или почему вам НЕ НУЖНЫ гигабайты памяти

Как Windows работает с ОЗУ или почему вам НЕ НУЖНЫ гигабайты памяти

Почему все ГЕРМЕТИЗИРУЮТ неправильно?

Почему все ГЕРМЕТИЗИРУЮТ неправильно?

Claude Code 2.0: Масштабное обновление! (Изменит правила игры)

Claude Code 2.0: Масштабное обновление! (Изменит правила игры)

Kubernetes — Простым Языком на Понятном Примере

Kubernetes — Простым Языком на Понятном Примере

Я полностью перешел на Linux и больше НИКОГДА не установлю Windows

Я полностью перешел на Linux и больше НИКОГДА не установлю Windows

Я удалил ВЕСЬ ВЕБ в Windows 11. Что из этого вышло?

Я удалил ВЕСЬ ВЕБ в Windows 11. Что из этого вышло?

Как умерла мировая Фотоиндустрия

Как умерла мировая Фотоиндустрия

💥 АСЛАНЯН: ТРАМП ЖЕСТКО ОБЛАЖАЛСЯ С ИРАНОМ! Тегеран СПРЯТАЛ БОМБЫ. США целились НЕ ТУДА

💥 АСЛАНЯН: ТРАМП ЖЕСТКО ОБЛАЖАЛСЯ С ИРАНОМ! Тегеран СПРЯТАЛ БОМБЫ. США целились НЕ ТУДА

Он не знал, Что Это был Брюс Ли — Чемпион Бросил вызов Случайному Человеку в Зале

Он не знал, Что Это был Брюс Ли — Чемпион Бросил вызов Случайному Человеку в Зале

История Linux и UNIX! Кто породил ВСЕ современные системы!

История Linux и UNIX! Кто породил ВСЕ современные системы!

Как восстановить файлы и флешку одной командой  Реквием

Как восстановить файлы и флешку одной командой Реквием

Как описана ВТОРАЯ МИРОВАЯ в учебниках ЯПОНИИ

Как описана ВТОРАЯ МИРОВАЯ в учебниках ЯПОНИИ

Вся IT-база в ОДНОМ видео: Память, Процессор, Код

Вся IT-база в ОДНОМ видео: Память, Процессор, Код

Билл Гейтс В ПАНИКЕ: Windows 11 столкнулась с МИРОВЫМ отказом!

Билл Гейтс В ПАНИКЕ: Windows 11 столкнулась с МИРОВЫМ отказом!

© 2025 ycliper. Все права защищены.



  • Контакты
  • О нас
  • Политика конфиденциальности



Контакты для правообладателей: [email protected]