Solution 1: redirect to a file you can write to
Your current working directory is /
, which by default can only be modified by root. Type cd ~
to change to your home folder, or cd
followed by the path to a directory you can write to, then do it again.
Solution 2: redirect with sh
under sudo
Shell redirections are not passed along to programs. This means that even if execute a program under sudo
, redirection (like >>
) will still be performed under your account. This is what happens:
sudo ls -l /usr/bin >>/ls-output.txt
-------------------------------------------------------
| execute external program | redirect stdout | what your shell sees
| sudo | command to execute as root | what sudo sees
If you want to sudo
a redirect, you need to run a shell as root. You can do this:
sudo sh -c ' ls -l /usr/bin >>/ls-output.txt '
-------------------------------------------------------------------------------
| execute external program (pass the single-quoted string verbatim) | your shell
| sudo | command to execute as root | sudo
| sh | -c | execute external program | redirect stdout | root shell
That way, the redirect is part of a sh
invocation that is done under sudo
.
Solution 3: redirect with tee
under sudo
As Oli♦ suggested, you can also pipe your command into tee:
ls -l /usr/bin | sudo tee /ls-output.txt
-------------------------------------------------------------------------
| execute external program | pipe | execute external program | your shell
| sudo | command to execute as root | sudo
Note that the tee
is executed under sudo
, but not the ls
. This is because tee
needs root priveleges (to write to /ls-output.txt
), and ls
does not. If the program generating output did need root privileges, you would need to sudo
both of them.
sudo ls -l /root | sudo tee /ls-output.txt
--------------------------------------------------------------------------------
| execute external program | pipe | execute external program | your shell
| sudo | command to execute as root | sudo #1
| sudo | command to execute as root | sudo #2
Also, if you don't want the output displayed on the screen, you can add >/dev/null
to the very end of the line.