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

Читайте также:  Microsoft project аналог 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 действительно все красиво.

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

Источник

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)

Источник

In Linux how to make a file with a name that is current date and time

I want to make a file which name will be a current date and time. I can create a file with the touch command. Also I can get current time with the date command. So, I think, I need to somehow pipe the second command to the first one. How can I do that?

2 Answers 2

Use the return value from a shell expression as the argument to touch :

Result: A file named e.g. 2012-03-11_14-33-53 .

This answer assumes you’re using bash (it’s described in the man page section Command Substitution), but other shells will work the same or only slightly different.

@MdGao And described in the same section of the man page. I prefer the answer I gave though, here are a few reasons

@gasan Just surround it with » quotation marks. You can imagine the output of date replacing that part of the command line, and touch Sun Mar 11 14:48:31 CET 2012 would create files name Sun , Mar , etc. touch «Sun Mar 11 14:48:31 CET 2012» on the other hand works fine (except I’m not sure how good the colons will work).

Читайте также:  Net core runtime linux

@gasan Single quotes won’t work because they don’t allow command substitution or any other interpretation. See quoting in the Bash manual.

@gasan The difference is that content of single quotes isn’t evaluated. Try it with echo «$HOME» and echo ‘$HOME’ . That’s why I suggested use of » .

You can use more simple command

OK, since I know you’re reading this, I’ll go into a little more detail: Daniel’s answer gives a result in a known and totally controlled format. (1) The output from date typically shows the time as hh:mm:ss. Your answer results in filenames containing colons. This could cause an error on Windows-based file systems. (2) The raw output from a simple invocation of date is locale-dependent; i.e., customized to the local language. Try LANG=de_DE date and LANG=fr_FR date to see examples. … (Cont’d)

(Cont’d) … (2a) Therefore, in the (unlikely?) event that you ever change the language on your system, or you give your script and a collection of data files from your system to somebody whose system is configured for a different language, there will be a mismatch. (I’m not sure that this would be a real problem, but it would be an aesthetic issue.) (2b) I don’t know of any locale that does this, but there could theoretically be a locale where date writes the date as mm/dd/yy (or dd/mm/yy). … (Cont’d)

(Cont’d) … If you ever encountered such a system, you would have filenames containing slashes, and that will cause errors. (3) Daniel’s answer gives a result where lexicographical (i.e., alphabetical) order, as produced by ls or * , corresponds to chronological order. With your answer, all the Fri files will be at the beginning of any lexicographically sorted list, and Apr and Aug will appear before all the other months.

Источник

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 .

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:

Читайте также:  Linux чем нагрузить процессор

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