Создать файл текущей датой linux

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

Читайте также:  Создать установочную флешку kali 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).

Источник

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)

Читайте также:  Linux find all files with name recursively

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

Источник

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

Лучше используй %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 действительно все красиво.

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

Источник

Append date to filename in linux

I want add the date next to a filename («somefile.txt»). For example: somefile_25-11-2009.txt or somefile_25Nov2009.txt or anything to that effect Maybe a script will do or some command in the terminal window. I’m using Linux(Ubuntu). The script or command should update the filename to a new date everytime you want to save the file into a specific folder but still keeping the previous files. So there would be files like this in the folder eventually: filename_18Oct2009.txt , filename_9Nov2009.txt , filename_23Nov2009.txt

You may want yyyy-mm-dd instead of dd-mm-yyyy to get lexicographical sort of file names to also sort them chronologically.

7 Answers 7

Info/Summary

With bash scripting you can enclose commands in back ticks or parantheses. This works great for labling files, the following wil create a file name with the date appended to it.

Example Usage:

echo "Hello World" > "/tmp/hello-$(date +"%d-%m-%Y").txt" (creates text file '/tmp/hello-28-09-2022.txt' with text inside of it) 

Note, in Linux quotes are your friend, best practice to enclose the file name to prevent issues with spaces and such in variables.

Читайте также:  Linux журнал работы системы

This appends the date to the filename — in the example in the question the date needs to go between the file name and the extension.

It might not answer the full question, but it took me ages to find out to use backticks, so thank you. (As @MehdiLAMRANI says, I use them without the double quotes.)

1. Get the date as a string

This is pretty easy. Just use the date command with the + option. We can use backticks to capture the value in a variable.

You can change the date format by using different % options as detailed on the date man page.

2. Split a file into name and extension.

This is a bit trickier. If we think they’ll be only one . in the filename we can use cut with . as the delimiter.

$ NAME=`echo $FILE | cut -d. -f1 $ EXT=`echo $FILE | cut -d. -f2` 

However, this won’t work with multiple . in the file name. If we’re using bash — which you probably are — we can use some bash magic that allows us to match patterns when we do variable expansion:

Putting them together we get:

$ FILE=somefile.txt $ NAME=$ $ EXT=$ $ DATE=`date +%d-%m-%y` $ NEWFILE=$_$.$ $ echo $NEWFILE somefile_25-11-09.txt 

And if we’re less worried about readability we do all the work on one line (with a different date format):

$ FILE=somefile.txt $ FILE=$_`date +%d%b%y`.$ $ echo $FILE somefile_25Nov09.txt 

Can you give some more details on precisely what you want to do. So you have a file in a directory which you want to date stamp in this way. Is it just one file with the same name each time or could it be a number of files with a number of different name?

I’m still not clear on what you want to do. It says the script should update the filename «everytime you want to save the file into a specific folder». What is saving the file into the folder? Where is it coming from?

If you want to have the filename changed everytime somebody saves something to a certain directory, then you’ll need some filesystem monitor. Have a look at inotify (man inotify); you should be able to build something that way.

cp somefile somefile_`date +%d%b%Y` 

You can add date next to a filename invoking date command in subshell.

date command with required formatting options invoked the braces of $() or between the backticks ( `…` ) is executed in a subshell and the output is then placed in the original command.

The $(. ) is more preferred since in can be nested. So you can use command substitution inside another substitution.

Solutions for requests in questions

$ echo somefile_$(date +%d-%m-%Y).txt somefile_28-10-2021.txt $ echo somefile_$(date +%d%b%Y).txt somefile_28Oct2021.txt 

The date command comes with many formatting options that allow you to customize the date output according to the requirement.

  • %D – Display date in the format mm/dd/yy (e.g. : 10/28/21)
  • %Y – Year (e.g. : 2021)
  • %m – Month (e.g. : 10)
  • %B – Month name in the full string format (e.g. : October)
  • %b – Month name in the shortened string format (e.g. : Oct)
  • %d – Day of month (e.g. : 28)
  • %j – Day of year (e.g. : 301)
  • %u – Day of the week (e.g. : 4)
  • %A – Weekday in full string format (e.g. : Thursday)
  • %a – Weekday in shortened format (e.g. : Thu)

Источник

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