Linux добавить дату к имени файла

How do you put date and time in a file name?

I’m trying to execute a command and would like to put the date and time in the output file name. Here is a sample command I’d like to run. md5sum /etc/mtab > 2016_4_25_10_30_AM.log The date time format can be anything sensible with underscores. Even UTC if the AM and PM can’t be used.

You’re not piping, you’re redirecting. And the question would be the same if you weren’t redirecting. Updating title.

3 Answers 3

If you want to use the current datetime as a filename, you can use date and command substitution.

 $ md5sum /etc/mtab > "$(date +"%Y_%m_%d_%I_%M_%p").log" 

This results in the file 2016_04_25_10_30_AM.log (although, with the current datetime) being created with the md5 hash of /etc/mtab as its contents.

Please note that filenames containing 12-hour format timestamps will probably not sort by name the way you want them to sort. You can avoid this issue by using 24-hour format timestamps instead.

If you don’t have a requirement to use that specific date format, you might consider using an ISO 8601 compliant datetime format. Some examples of how to generate valid ISO 8601 datetime representations include:

 $ date +"%FT%T" 2016-04-25T10:30:00 $ date +"%FT%H%M%S" 2016-04-25T103000 $ date +"%FT%H%M" 2016-04-25T1030 $ date +"%Y%m%dT%H%M" 20160425T1030 

If you want «safer» filenames (e.g., for compatibility with Windows), you can omit the colons from the time portion.

Please keep in mind that the above examples all assume local system time. If you need a time representation that is consistent across time zones, you should specify a time zone offset or UTC. You can get an ISO 8601 compliant time zone offset by using «%z» in the format portion of your date call like this:

 $ date +"%FT%H%M%z" 2016-04-25T1030-0400 

You can get UTC time in your date call by specifying the -u flag and adding «Z» to the end of the datetime string to indicate that the time is UTC like this:

 $ date -u +"%FT%H%MZ" 2016-04-25T1430Z 

Источник

unixforum.org

Подскажите, как в bash можно в имя создаваемого файла подставить текущую дату (год-месяц-день:часы:минуты:секунды)?

Re: Решено: Запихать дату в имя файла

Сообщение madskull » 25.01.2005 10:41

Re: Решено: Запихать дату в имя файла

Сообщение alexsf » 25.01.2005 10:55

Класс, практически получилось.

В итоге получил файл file-2005-01-25:

Все, что после первого двоеточия в имя файла не вошло. Попробовал : заменить на . — то же самое. Что я неправильно делаю.
alexsf добавил в 25.01.2005 10:55
Ошибочка. Не то, чтоб не вошло — всё, что после двоеточия получилось отдельным файлом

Re: Решено: Запихать дату в имя файла

Сообщение madskull » 25.01.2005 10:59

Читайте также:  Установка lineage сервер linux

Лучше используй %H (00-23)
Если время меньше десяти часов, то печатаются пробел и час => получается имя с пробелом => в понятии touch — два файла.
кстати, у тебя должен был получиться еще один файл, вроде 9:10:11. Неужели он не навел на размышления?

Re: Решено: Запихать дату в имя файла

Сообщение alexsf » 25.01.2005 11:19

(madskull @ Вторник, 25 Января 2005, 10:59) писал(а): Лучше используй %H (00-23)
Если время меньше десяти часов, то печатаются пробел и час => получается имя с пробелом => в понятии touch — два файла.
кстати, у тебя должен был получиться еще один файл, вроде 9:10:11. Неужели он не навел на размышления?

Действительно, файл получился. И на размышления навел, но додуматься я не смог А с использованием %H действительно все красиво.

Появился еще вопрос: а как мне переименовать файл в такой формат? И запомнить имя получившегося файла в переменной?

Источник

⏱️ Как создать каталоги или файлы с именами на текущую дату/время/месяц/год на Linux

Вы когда-нибудь хотели создать каталог или файл и назвать его текущей датой / временем / месяцем / годом из командной строки в Linux?

Это будет полезно, если вы хотите что-то сохранить, например, фотографии, в каталогах с указанием даты, когда они действительно были сделаны.

Показанные далее команды создадут каталоги или файлы с именами с текущей датой или временем на основе часов вашего компьютера.

Создание каталогов или файлов с именами текущей даты / времени / месяца / года на Linux

Чтобы создать каталог и назвать его текущей датой, просто запустите:

Эта команда создаст каталог и назовет его сегодняшней датой в формате dd: mm: yyyy.

Аналогично, чтобы создать файл с текущей датой, временем, месяцем, годом, просто замените «mkdir» командой «touch»:

Создание каталогов или файлов с произвольным именем с текущей датой

Как насчет пользовательского имени для каталога или файла с датой / временем / месяцем / годом?

Создание каталогов файлов в формате ISO

Если вы хотите использовать формат даты ISO (например, 2020-06-06), запустите:

Все вышеперечисленные три команды дают одинаковый результат.

Для создания файлов просто замените mkdir командой «touch».

Больше примеров

Если вы хотите только день текущей даты, используйте:

Эта команда создаст каталог только с текущим днем в имени. т.е. 06.

Точно так же вы можете создавать каталоги с именем текущего месяца только в имени:

Обратите внимение что S – заглавная

Чтобы назвать каталог с текущими минутами, используйте заглавную M:

Во всех приведенных выше примерах мы создали каталоги с номерами на их именах.

Что если вы хотите назвать каталоги с фактическим названием текущего дня / месяца, например, Saturday, October и т. д.?

Вот список поддерживаемых операторов, которые вы можете использовать для именования каталогов с указанием текущего дня, месяца, времени, года, дня недели, дня месяца, часового пояса и т. д.

 %a locale's abbreviated weekday name (e.g., Sun) %A locale's full weekday name (e.g., Sunday) %b locale's abbreviated month name (e.g., Jan) %B locale's full month name (e.g., January) %c locale's date and time (e.g., Thu Mar 3 23:05:25 2005) %C century; like %Y, except omit last two digits (e.g., 20) %d day of month (e.g., 01) %D date; same as %m/%d/%y %e day of month, space padded; same as %_d %F full date; same as %Y-%m-%d %g last two digits of year of ISO week number (see %G) %G year of ISO week number (see %V); normally useful only with %V %h same as %b %H hour (00..23) %I hour (01..12) %j day of year (001..366) %k hour, space padded ( 0..23); same as %_H %l hour, space padded ( 1..12); same as %_I %m month (01..12) %M minute (00..59) %n a newline %N nanoseconds (000000000..999999999) %p locale's equivalent of either AM or PM; blank if not known %P like %p, but lower case %q quarter of year (1..4) %r locale's 12-hour clock time (e.g., 11:11:04 PM) %R 24-hour hour and minute; same as %H:%M %s seconds since 1970-01-01 00:00:00 UTC %S second (00..60) %t a tab %T time; same as %H:%M:%S %u day of week (1..7); 1 is Monday %U week number of year, with Sunday as first day of week (00..53) %V ISO week number, with Monday as first day of week (01..53) %w day of week (0..6); 0 is Sunday %W week number of year, with Monday as first day of week (00..53) %x locale's date representation (e.g., 12/31/99) %X locale's time representation (e.g., 23:13:48) %y last two digits of year (00..99) %Y year %z +hhmm numeric time zone (e.g., -0400) %:z +hh:mm numeric time zone (e.g., -04:00) %::z +hh:mm:ss numeric time zone (e.g., -04:00:00) %. z numeric time zone with : to necessary precision (e.g., -04, +05:30) %Z alphabetic time zone abbreviation (e.g., EDT)

Источник

Читайте также:  Alt linux консультант плюс

Bash: Добавить текущую дату и метку времени к имени файла

При написании Bash сценариев иногда возникает необходимость включать в имена файлов информацию о текущей дате или метке времени, особенно когда файлы создаются регулярно, например, ежемесячно/ежедневно/ежечасно, для резервного копирования создания логов и других целей.

Инструмент date командной строки linux позволяет форматировать отображение текущего времени по своему усмотрению.

Синтаксис команды date выглядит следующим образом:

Включить текущее время с точностью до секунды:

now=$(date+"%Y-%m-%d-%S") filename="log_name.$now.log" # example: log_name.2022-02-16-39.log

Включить текущую метку времени с точностью до наносекунды:

now=$(date +"%Y.%m.%d.%S.%N") filename="log_name.$now.log" # example: log_name.2022.02.16.47.169617000.log

Включить текущую временную метку (т.е. количество секунд, прошедших с 1970-1-1):

now=$(date +"%s") filename="log_name.$now.log" # example : log_name.1644992228.log

Наиболее распространенные символы форматирования для команды data:

%Y — Год (например, 2022)
%m — Месяц (01-12)
%B — Длинное название месяца (например, November )
%b — Краткое название месяца (например, Nov )
%d — День месяца (например, 01)
%j — День года (001-366)
%u — День недели (1-7)
%A — Полное название дня недели (например, Friday )
%a — Краткое название дня недели (например, Fri )
%H — Час (00-23)
%I — Час (01-12)
%M — Минута (00-59)
%S — секунда (00-60)

Источник

Appending a current date from a variable to a filename

However all I get is the name of the file, and it appends nothing. How do I append a current date to a filename?

when you apppand date, make sure not to use : because then it will be read as a host in rsync and scp. stackoverflow.com/a/37143274/390066

5 Answers 5

More than likely it is your use of set . That will assign ‘today’, ‘=’ and the output of the date program to positional parameters (aka command-line arguments). You want to just use C shell (which you are tagging this as «bash», so likely not), you will want to use:

today=`date +%Y-%m-%d.%H:%M:%S` # or whatever pattern you desire 

Notice the lack of spaces around the equal sign.

You also do not want to use & at the end of your statements; which causes the shell to not wait for the command to finish. Especially when one relies on the next. The find command could fail because it is started before the mkdir .

Читайте также:  Linux ping one time

Bash script to inject a date into a filename:

This bash code in file called a.sh

#!/bin/bash today=`date '+%Y_%m_%d__%H_%M_%S'`; filename="/home/el/myfile/$today.ponies" echo $filename; 

When run, prints:

eric@dev ~ $ chmod +x a.sh eric@dev ~ $ ./a.sh /home/el/myfile/2014_08_11__15_55_25.ponies 

Explanation of the code:

Interpret the script with the /bin/bash interpreter. Make a new variable called today. Execute the date command, passing in the Y, m, d, H, M, S flags to configure the output. Place the result into the date variable.

Create a new variable called filename, surround the $today variable with the rest of the static filename text. then echo the filename to screen.

Cram it into a one-liner to increase lulz:

echo "/home/el/myfile/`date '+%Y_%m_%d__%H_%M_%S'`.ponies" 

You seem to have mixed up several things.

set today = ‘date +%Y’ looks like tcsh syntax, but even in tcsh it assigns the string date +%Y to the variable today , it doesn’t run the date command. As you’re probably using bash or some other POSIX shell, the syntax of an assignment is today=some_value (with no spaces around the equal sign). To run the command and assign its output to the variable, use command substitution:

(I’ve also completed the date specification). You can use backquotes instead of dollar-parentheses, but it’s prone to being visually confused with forward quotes, and the rules for when you need quotes inside a backquoted command are pretty complex and implementation-dependent, so it’s better not to stick to $(…) (which has the same effect with a saner syntax).

You used & at the end of several commands. That makes the command execute in the background, which is not wanted here. I suspect you meant && , which means to execute the next command only if the first command succeeded.

today=$(date +%Y-%m-%d) mkdir -p The_Logs && find … 

An alternative to using && after each command is to start your script with set -e . This tells the shell to stop executing the script as soon as any command returns a nonzero status (except for commands in if conditions and a few other cases).

set -e today=$(date +%Y-%m-%d) mkdir -p The_Logs find … 

Your find command is fine but probably doesn’t do what you intend to do (though I don’t know for sure what that is).

You’re creating a directory with mkdir and then immediately traversing it with find . That won’t be useful unless the directory already exists. Did you mean to create a directory for today’s logs and move recent files from The_Logs to a directory called e.g. The_Logs.2012-02-11 ?

mkdir -p "The_Logs.$today" find The_Logs -mtime -1 -exec mv <> "The_Logs.$today" \; 

Or did you mean to rename today’s log files to add the suffix $today ? That requires calculating the different file name for each file to move.

find The_Logs -mtime -1 -exec sh -c 'mv "$0" "$0.$today"' <> \; 

Note that I used -mtime , to move files based on their modification time, and not -atime , which is the time the file was last read (if your system keeps track of that — if it doesn’t, the atime may be as far back as the mtime).

Источник

Оцените статью
Adblock
detector