How could I overwrite file hosts in OS X?

1

Well, in my company I have to change file hosts to map the domain to the LAN IP because our servers located here. Then when I arrive to home, I have to change hosts file again to comment out which IP I used at company.

I write this bash function to overwrite my /etc/hosts but no luck...

# Change host file function
chosts() {
   [ "$1" == "-h" ] && sudo cp ~/.local/hosts/hosts.home /etc/hosts
   [ "$1" == "-c" ] && sudo cp ~/.local/hosts/hosts.com /etc/hosts
}

I want to know why I can't copy or move my file to /etc/hosts and I also need a solution to do this trick.

Any help will be appreciated.

Thanks.

Toan Nguyen

Posted 2015-01-16T02:20:43.393

Reputation: 131

+1, what's the error though? – Louis – 2015-01-16T02:25:41.253

@Louis: No error, nothing happens just can't overwrite it. After I executed the function, then check hosts file, no changes made to it. – Toan Nguyen – 2015-01-16T02:54:41.783

Okay, but If something gets logged ('console.app' is good for checking), your answer might be in a clue left there. – Louis – 2015-01-16T02:59:59.310

not really my forte, but isn't etc/hosts a symlink to private/etc/hosts ? I heard editing that directly gets better results. – Tetsujin – 2015-01-16T08:58:12.167

@Tetsujin: Could you describe more about that? – Toan Nguyen – 2015-01-16T10:06:15.613

It's above my pay grade really [I tend to do it the Dummies way, TextEdit or GasMask] but there was a whole lot of mumbling about it on MacRumours if that might help you.

– Tetsujin – 2015-01-16T10:12:53.750

@Tetsujin: Wow, you are the saint. Thank you so much !!! – Toan Nguyen – 2015-01-16T15:52:31.237

Welcome;-) If you find a definitive answer, post it as such & mark it correct, for future searchers – Tetsujin – 2015-01-16T16:06:56.207

Answers

2

Use this function to overwrite hosts files!

chosts() {
   [ "$1" == "-h" ] && sudo cp ~/.local/hosts/hosts.home /private/etc/hosts
   [ "$1" == "-c" ] && sudo cp ~/.local/hosts/hosts.com /private/etc/hosts
}

Small notice

Remember to keep hosts.home and hosts.com with permission root:wheel

Toan Nguyen

Posted 2015-01-16T02:20:43.393

Reputation: 131

Glad you got it. Mark the answer as correct - then it scores better in future searches. – Tetsujin – 2015-01-17T11:56:19.493