Unix/Linux — Redirect output with sudo


Sometimes you might need to redirect the output with sudo privileges. For example:

echo myhost.com > /etc/hostname

will give you the following error:

-bash: /etc/hostname: Permission denied

Unfortunately, using:

sudo echo myhost.com > /etc/hostname

will give the same error.

The solution is to start bash as sudo and then give the entire command to bash as input:

sudo bash -c “echo myhost.com > /etc/hostname”

Or as one reader suggested:

echo myhost.com | sudo tee /etc/hostname


7 Responses to “Unix/Linux — Redirect output with sudo”

  1. foobarnl Says:

    A better way to do this (minimise root usage) is to run:

    echo myhost.com | sudo tee /etc/hostname

  2. marzvix Says:

    Really good point!

    EMFJI If you want to create the file with one ig/gid, better to add -u option in sudo command.

    $ echo “bla bla bla” | sudo -u one tee /home/one/blablabla.file


  3. eric3chang Says:

    If you don’t want the echo to appear, you can do
    $ echo “bla bla bla” | sudo -u one tee /home/one/blablabla.file &> /dev/null

  4. mainstreet web hosting Says:

    mainstreet web hosting…

    […]Unix/Linux — Redirect output with sudo « Not So Frequently Asked Questions[…]…

  5. Django Janny (@keltroth) Says:

    If you wish to keep the content of your original /etc/hostname file you should do :

    $ echo myhost.com | sudo tee -a /etc/hostname

    where -a is shorthand for –append


  6. Redirect output with sudo command – pitsanublog Says:

    […] คัดลอกมาจาก notfaq.wordpress.com […]

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: