1

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
  • what is the purpose of the tail? Do you want to discard the earlier lines? Jan 14, 2016 at 23:35
  • i want to keep a 10 line log
    – autorun
    Jan 15, 2016 at 0:59

3 Answers 3

3

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.

1

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.

0

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .