I\'ve been given sudo access on one of our development RedHat linux boxes, and I seem to find myself quite often needing to redirect output to a location I don\'t normally h
This is based on the answer involving tee
. To make things easier I wrote a small script (I call it suwrite
) and put it in /usr/local/bin/
with +x
permission:
#! /bin/sh
if [ $# = 0 ] ; then
echo "USAGE: <command writing to stdout> | suwrite [-a] <output file 1> ..." >&2
exit 1
fi
for arg in "$@" ; do
if [ ${arg#/dev/} != ${arg} ] ; then
echo "Found dangerous argument ‘$arg’. Will exit."
exit 2
fi
done
sudo tee "$@" > /dev/null
As shown in the USAGE in the code, all you have to do is to pipe the output to this script followed by the desired superuser-accessible filename and it will automatically prompt you for your password if needed (since it includes sudo
).
echo test | suwrite /root/test.txt
Note that since this is a simple wrapper for tee
, it will also accept tee's -a
option to append, and also supports writing to multiple files at the same time.
echo test2 | suwrite -a /root/test.txt
echo test-multi | suwrite /root/test-a.txt /root/test-b.txt
It also has some simplistic protection against writing to /dev/
devices which was a concern mentioned in one of the comments on this page.
Someone here has just suggested sudoing tee:
sudo ls -hal /root/ | sudo tee /root/test.out > /dev/null
This could also be used to redirect any command, to a directory that you do not have access to. It works because the tee program is effectively an "echo to a file" program, and the redirect to /dev/null is to stop it also outputting to the screen to keep it the same as the original contrived example above.
Make sudo run a shell, like this:
sudo sh -c "echo foo > ~root/out"