Linux filename date time

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 

Источник

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.

Читайте также:  Linux терминал остановить процесс

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:

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).

Читайте также:  Postgresql сменить пароль пользователя linux

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).

Источник

How can I add datetime to an existing file name in Linux?

I want to add date and time to the file name, for example: 08032016out.log.zip This is what I try to do:

_now=$(date +"%m_%d_%Y") _file="$_nowout.log" touch $_file.txt # creating new file with the timedate 

I very strongly recommend using YYYYMMDD rather than DDMMYYYY. YYYYMMDD is the only format that sorts correctly, which (along with the fact that it’s unambiguous) is why it’s the ISO standard recommended date format (see en.wikipedia.org/wiki/ISO_8601)

2 Answers 2

You have created a variable named _now , but later you reference a variable named _nowout . To avoid such issues, use curly braces to delimit variable names:

_now=$(date +"%m_%d_%Y") _file="$out.log" touch "$_file.txt" 

Note that I have left «$_file.txt» as is, because . is already a variable names delimiter. When in doubt, «$.txt» could be used just as well.

Bonus 1: $ syntax actually provides several useful string operations on variables, in addition to delimiting.

Bonus 2: creative shell escaping and quoting can also be used to delimit variable names. You could quote the variable and the string literal separately (i.e. file=»$_now»»out.log» or file=»$_now»‘out.log’ ) or leave one of the parts unquoted (i.e. file=$_now»out.log» or file=»$_now»out.log ). Finally, you can escape a single character which follows your variable name: file=$_now\out.log . Though I wouldn’t recommend reusing these examples without good understanding of shell quoting and escaping rules.

Источник

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?

Читайте также:  Lan speed test linux

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).

@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.

Источник

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