0

When I'm on a work VPN I need to access a particular internal site but I need to tunnel through SSH through one of our dev servers to get to it. This is fine.

However whenever I need to do this, I need to add an entry to the hosts file to alias this particular domain to localhost and do the SSH tunnelling, and consequently when I've finished I need to remove the entry from the hosts file. I thought I'd automate this which is relatively easy. However managing the hosts file is not as easy as I thought:

I've tried:

cat /etc/hosts | grep -v 'internal.name.company.com' > /etc/hosts

However this always results in an empty /etc/hosts file. If I run cat /etc/hosts | grep -v 'internal.name.company.com' I get the output I want exactly. Am I missing something obvious? When I redirect the output to another file, say ~/test the result is as expected and this file contains the contents I expect.

Sam Giles
  • 650
  • 6
  • 16

2 Answers2

4

Try this way:

grep -v 'internal.name.company.com' /etc/hosts > /tmp/hosts.tmp ; cp /tmp/hosts.tmp /etc/hosts
Kamil Budziewski
  • 22,699
  • 14
  • 85
  • 105
Valeriy
  • 41
  • 1
0

You can also use sed to modify the file directly:

sed '/internal\.name\.company\.com/d' hosts
konsolebox
  • 72,135
  • 12
  • 99
  • 105