Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

This question already has an answer here:

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?

share|improve this question

marked as duplicate by Eliah Kagan, Aditya, Sylvain Pineau, Warren Hill, Andrea Corbellini Sep 22 at 16:24

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.

3  
Can you clarify? You want to know why you should warp the redirection while using sudo or in which cases you have to run subshells? –  Braiam May 29 at 23:25
1  
Can you clarify? In your examplesudo sh -c ... doesn't create a subshell, but a new shell process (and you don't need this new shell as long as you can use sed or tee or something else instead of >>). And >> is not a real command to use sudo on it, but is an redirection operator. So, your question doesn't have sense, or logic... –  Radu Rădeanu May 30 at 10:40

1 Answer 1

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
share|improve this answer
    
Using the pipeline, you are using in fact not one subshell, but two. See man bash in this sense (line 279): "Each command in a pipeline is executed as a separate process (i.e., in a subshell)." –  Radu Rădeanu May 30 at 19:08

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