Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a file with todays date in the filename [duplicate]

Tags:

linux

bash

Command 1:

$ touch test"date"

Command 2:

$ date +"%F"
2018-01-16

I want to be able to run the command so the file test_2018-01-16 is created. How do or can I combine the 2 commands above to do this?

$ touch test_"date"

EDIT1 - Answer

tks

these commands

touch fred-`date +%F`
touch "test-$(date +%F)"
touch "test2_$(date +"%F %T")"

prduce the following files respectively

fred-2018-01-16
test-2018-01-16
test2_2018-01-16 11:51:53
like image 302
HattrickNZ Avatar asked Jan 15 '18 21:01

HattrickNZ


People also ask

How do I add timestamp to filename?

%M. %S") echo "Current Time : $current_time" new_fileName=$file_name. $current_time echo "New FileName: " "$new_fileName" cp $file_name $new_fileName echo "You should see new file generated with timestamp on it.."

How do you write the time in a filename?

I'd use YYYY-MM-DD HHmmss for filenames, unless there is a particular need for timezones or a possible need to parse them into ISO dates; in those cases an ISO date would probably be preferrable.

How do you create a filename with a date and time in python?

First, import the module and then get the current time with datetime. now() object. Now convert it into a string and then create a file with the file object like a regular file is created using file handling concepts in python.


2 Answers

You should use double quotes and need to evaluate date +"%F" using command substitution.

  $ touch "test_$(date +%F)"

This will create an empty file test_2018-01-15

Double quote helps you create a single file where some options of date command would include a space.

For example, touch test_$(date) will create multiple files, where as touch "test_$(date)" won't.

As pointed out by OP, one would need additional quotes " around the format options, when multiple of them are used:

touch "test_$(date +"%F %T")" 
like image 178
iamauser Avatar answered Nov 09 '22 02:11

iamauser


In my world (with Bash) its:

touch fred-`date +%F`

where 'fred-' is the prefix and teh date command provides the suffix

like image 30
Mike Tubby Avatar answered Nov 09 '22 02:11

Mike Tubby