Redirecting stdout to a file you don't have write permission on
Yes, using tee
. So echo test > /tmp/foo
becomes
echo test | sudo tee /tmp/foo
You can also append (>>
)
echo test | sudo tee -a /tmp/foo
To replace the content of the file with the output of echo
(like the >
shell redirection operator).
echo test | sudo dd of=/tmp/foo
To write into the file (at the beginning, though you can use seek
to output at different offsets) without truncating (like the 1<>
Bourne shell operator):
echo test | sudo dd of=/tmp/foo conv=notrunc
To append to the file (like >>
), with GNU dd
:
echo test | sudo dd of=/tmp/foo oflag=append conv=notrunc
See also GNU dd
's conv=excl
to avoid clobbering an existing file (like with set -o noclobber
in POSIX shells) and conv=nocreat
for the opposite (only update an existing file).
tee
is probably the best choice, but depending on your situation something like this may be enough:
sudo sh -c 'echo test > /tmp/foo'