I can create a new file and put the date in it.
touch example.txt
date >> example.txt
But I must create the file with the date in it the moment I created the new file. How do I do that with only one command?
Simply use the date command to redirect into file and it will be created:
date > example.txt
A prefered way would using the >>
append operator:
date >> example.txt
Both the redirection operator (>
) and the append operator (>>
) will create the target file if it doesn't exist. You never need to create it first and write to it later.
>
will clear the file if it does exist, whereas >>
as in the OP's original sequence will add the date to the end of the file if it already exists.
Dec 7, 2018 at 17:42
>
should be enough!
Dec 7, 2018 at 17:53
>>
when I know the file is not supposed to exist. It's easier to recover from a mistaken use of >>
than to recover from a mistaken use of >
.
It's worth noting that, if the problem with
I must create the file with the date in it the moment I created the new file
is due to race conditions (e.g. there's a process periodically scanning for a file with that name, and expects to find a date in there), even doing
date > example.txt
isn't correct, as there's still a very small window between when the shell opens the file and when date
actually writes its stuff (which may also be written non-atomically as well).
In that case, the solution is to write to a separate file and then perform a mv
to the correct file name:
date > example.txt.tmp
mv example.txt.tmp example.txt
A move on the same file system is guaranteed to be atomic, so when example.txt
appears, it already contains the expected content.
If instead the question is just about typing a single command, the original solution is of course the correct and most straightforward one.
date > ...
still isn't atomic, so that additional mv
step still doesn't help the race condition. Example: date +%Y-%m-%d\ %H:%M:%S.%N > foo && stat foo && cat foo
.
date > ...
isn't atomic - I even said that ("which may also be written non-atomically as well"). The rename of course is effective only if the other program looks specifically for the final filename, not just any file in the directory.
Dec 11, 2018 at 0:23
touch
updates the modification time of a file, or creates the file if it does not exist. Since the file would be created with the redirection>>
or>
anyway, this command is unnecessary here.