Linux file name with date

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:

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

Читайте также:  Переключение контекста процесса 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 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.

Читайте также:  Astra linux safenet authentication client

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 

Источник

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

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

Читайте также:  Shutdown system in linux

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

Источник

Get today’s date and use it in filename

Using the command-line, I want to create a log file with today’s date in the name (for example, today is 05/17/2011, so the filename would have to be log051711 ). I know how to create the file ( touch filename ), but I don’t know how to get today’s date. I have looked at the manual for date , but it seems that I can’t really format its output? Any help would be appreciated.

5 Answers 5

You can format the output using the ‘+FORMAT’ parameter, e.g.

See the manpage for what sequences you can use in FORMAT.

I just figured out that to use this in a cron job, I had to escape the %-signs, so that it read: touch «log$(date +’\%m\%d\%y’)»

True.. MyFileName is just a prefix.. If needed we can keep it, else.. echo date +»%d-%m-%Y» this is enough. it will print only date 21-02-2014

Ah, now I see: I got confused because the ` did not appear in your answer. This is because they are used by askubuntu to indicate code blocks. You should mark code by either surrounding it with backticks or by indenting the paragraph with the code with 4 spaces. For starters you probably should use the menu above the editor for that and check your post in the preview below the textbox before submitting.

One of the possible soultions:

I’m sure somebody else has a better way to do this but assuming you want month-day-year this should work:

and you can reorder the %m, %d, %Y to reflect the ordering you want. The man page for date tells you more about additional formats.

Python can do this job as well. The small script for that would be the following:

#!/usr/bin/env python import time,os date=time.gmtime() month = str(date.tm_mon).zfill(2) day=str(date.tm_mday).zfill(2) year=str(date.tm_year)[-2:] fname = 'log' + month + day + year with open(fname,'a') as f: os.utime(fname,None) 

The idea here is simple: we use time.gmtime() to get current date, extract specific fields from the structure it returns, convert appropriate fields to strings, and create filename with the resulting name.

$ ls touch_log_file.py* $ ./touch_log_file.py $ ls log010317 touch_log_file.py* 

At the moment of writing it is January 3rd , 2017. Thus the resulting filename is appropriately month,day,year — log010317

Источник

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