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.

3
  • cat foo.txt | head -n-1 > foo.txt Apr 11, 2016 at 10:10
  • @PiyushJain That appears to have the same issue. Apr 11, 2016 at 11:21
  • cat lol.txt 1 2 3 4 5 6 7 8 cat lol.txt | head -n-1 > lol.txt cat lol.txt 1 2 3 4 5 6 7 Apr 11, 2016 at 11:29

1 Answer 1

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)

3
  • Or use ksh93 and its <>; redirection operator, or use GNU truncate after having determined the size of the last line. Apr 11, 2016 at 9:49
  • I'm afraid I still don't quite understand why this results in foo.txt being empty. Apr 11, 2016 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, 2016 at 12:27

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