Velvet Star Monitor

Standout celebrity highlights with iconic style.

news

`tail` and append in oneliner

Writer Emily Wong

How could I tail and append a text in a file, in one line, in Bash?

My failed attempt would be

tail file.txt > file.txt && date >> file.txt
2

3 Answers

This produces unexpected results:

tail file.txt > file.txt && echo $(date) >> file.txt

The first redirection truncates the file before the tail process starts, so tail is now operating on an empty file. (ref)

2 suggestions:

  1. a temp file:

    f=file.txt
    tmp=$(mktemp)
    { tail "$f"; date; } > "$tmp" && mv "$tmp" "$f"
  2. sponge from the moreutils package

    f=file.txt
    { tail "$f"; date; } | sponge "$f"

Note that echo $(date) is redundant: you don't need echo to send the output of date to stdout -- date does this by default.

Another way without using temporary files or installing additional tools (but not efficient for large files):

<<<"$(<file)" tail >file && date >>file

This reads file in a command substitution, guaranteeing that the reading of file will take place before the other redirections are resolved.

You can use Vim in Ex mode:

ex -sc '1,-10d|x' file.txt
  1. 1,-10 select all but last 10 lines

  2. d delete

  3. x save and close

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy