Bash – How to Redirect Shell Stdout to the First Line of a File

bashshell

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:

{ date; cat file; } >file.new && mv file.new file

Discussion

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

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

  3. echo `date` >> test.txt can be replaced by a simpler and more efficient date >> 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.

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

Related Question