Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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
add comment

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.

1 Answer

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
add comment

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