How to use sudo with pipelines? [duplicate]
Possible Duplicate:
sudo & redirect output
Let's say I want to add some line into /etc/profile. I try:
$ sudo echo "something" >> /etc/profile
bash: /etc/profile: Access forbidden
Of course I could write:
$ sudo su
# echo "something" >> /etc/profile
and this works, however it does not work within a shell script.
So, what is the right way?
Solution 1:
You can use tee
:
$ echo "something" | sudo tee -a /etc/profile
If you omit the -a
(append) the file will be overwritten.
Solution 2:
Your version:
sudo echo "something" >> /etc/profile
In this command, echo
is run as root, but the shell that's redirecting echo
's output to the root-only file is still running as you. That's why you are getting "Access forbidden"
Working version:
sudo bash -c 'echo "something" >> /etc/profile'
In this command you use sudo to start a new shell with root privileges and then give that shell the whole command string (including the redirection) with the -c option of bash.