The shell standard output redirects to the last line of the file, is there a way to write it to the first line of the file?
Since the content of stdout is unpredictable, I suspect that this may require changing the default behavior of stdout, but I am not sure if it is feasible.
Example, redirecting a timestamp to file
echo `date` >> test.txt
Default save to last line of file
Mon Aug 31 00:40:27 UTC 2020
Mon Aug 31 00:40:28 UTC 2020
Mon Aug 31 00:40:29 UTC 2020
Mon Aug 31 00:40:30 UTC 2020
Desired effect, save the output to the first line of the file
Mon Aug 31 00:40:30 UTC 2020
Mon Aug 31 00:40:29 UTC 2020
Mon Aug 31 00:40:28 UTC 2020
Mon Aug 31 00:40:27 UTC 2020
Thanks in advance!
Best Answer
To write the date to the beginning instead of the end of
file
, try:Discussion
Adding new text to the beginning of a file requires the whole file to be rewritten. Adding new text to the end of a file only requires writing the new text.
Andy Dalton's suggestion of just appending to the end of a file like normal and then using
tac file
to view the file is a good one.echo `date` >> test.txt
can be replaced by a simpler and more efficientdate >> test.txt
.If one is using bash 4.3 or later then, as Charles Duffy points out,
printf '%(%c)T\n' -1 >>test.txt
is still more efficient.The spaces around the curly braces are essential. This is because
{
and}
are shell reserved words (as opposed to shell keywords which do not require spaces).