0

I was recently looking for a way to remove the last line of a file foo.txt and came across the following solution

head -n -1 foo.txt temp.txt; mv temp.txt foo.txt

which works fine. However, I also tried simply

head -n -1 foo.txt > foo.txt

which to my surprise left foo.txt an empty text file, and I would like to know why.

I'm just getting started with unix, so it's possible my question is rather silly.

1 Answers1

2

Because the redirect > happens before the rest of the command.

If you want to do an inplace edit, you'll need a suitably aware utility. e.g. perl or sed. (Or just do the mv like the original snippet suggested)

Sobrique
  • 4,404
  • 14
  • 24
  • Or use `ksh93` and its `<>;` redirection operator, or use GNU `truncate` after having determined the size of the last line. – Stéphane Chazelas Apr 11 '16 at 09:49
  • I'm afraid I still don't quite understand why this results in foo.txt being empty. – Étienne Bézout Apr 11 '16 at 11:25
  • 2
    Because `>` opens and truncates the file, ready to have data put into it. And then the rest of the command happens to fill it with data... so it's already empty _before_ you start reading it. – Sobrique Apr 11 '16 at 12:27