1

I have to run this command sudo sh -c "echo 'nameserver 8.8.8.8' >> /etc/resolv.conf" to append a line nameserver 8.8.8.8 into /etc/resolv.conf file. I know, it could be possible only through subshell.

My questions:

  • Is that it could be possible without running the command in subshell?

  • On which cases, a command should be runned in subshell?

Avinash Raj
  • 80,446

1 Answers1

6
sudo echo 'nameserver 8.8.8.8' >> /etc/resolv.conf

fails because it gives elevated permissions to the echo command (which doesn't need it), but not to the >> redirection (which does, since the destination file is owned by root). Wrapping the whole command sequence in sudo sh overcomes that.

You could also do

echo 'nameserver 8.8.8.8' | sudo tee -a /etc/resolv.conf
steeldriver
  • 142,475