1

I'm trying to add to the hosts file a certain IP. This IP can be retrieved with 2 different commands, but the best one doesn't always return it.

I'm trying to write a single command which checks the first command and if it returns an IP, add the line to the file, else use the second command.

Priority command:

docker network inspect bridge | grep Gateway | grep -o -E '[0-9\.]+'

Alternative command:

ifconfig docker | grep -oP 'inet:\K[^ ]+'

I've tried to write an if-else command using -eq '' or -ne 0 but I can't make it work when I try to use it as a parameter to add the line in the hosts file.

It could be something like this (but in one line shell command):

if [ docker network inspect bridge | grep Gateway | grep -o -E '[0-9\.]+' -ne 0 ] ;
  then sudo echo $(docker network inspect bridge | grep Gateway | grep -o -E '[0-9\.]+') "symfony.dev" >> /etc/hosts;
  else sudo echo $(ifconfig docker0 | awk '/inet:/{ print substr($2,6); exit }') "symfony.dev" >> /etc/hosts;
fi
3

1 Answer 1

1

The collected output of an if statement can be redirected or piped as with any other command.

if ! docker network inspect bridge | grep Gateway | grep -o -E '[0-9\.]+'; then
    ifconfig docker | grep -oP 'inet:\K[^ ]+'
fi | sudo tee -a /etc/hosts > /dev/null

The only part of this that requires root permission is opening /etc/hosts for writing, so I've replaced output redirection with sudo tee.

You must log in to answer this question.

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