Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Possible Duplicate:
How can I make iconv replace the input file with the converted output?

I'm writing a script to change the content of my hosts file but I got stuck on the head output redirection.

If I do head -n -1 hosts >hosts my hosts file will result empty and yes, it has more than 1 line.

share|improve this question

marked as duplicate by Gilles, Renan, Caleb, warl0ck, Mat Nov 28 '12 at 6:26

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

up vote 2 down vote accepted

That's because your shell truncates the file when you redirect to it. This happens before head gets a chance to read it.

You can either use a temporary file:

head -n1 hosts > hosts.tmp && mv hosts.tmp hosts

Or use sponge from the moreutils packate:

head -n1 hosts | sponge hosts
share|improve this answer
Ok, that makes sense! Thanks a lot! – Esolitos Nov 25 '12 at 17:23

Not the answer you're looking for? Browse other questions tagged or ask your own question.