Home | Catalogue | Robert's Blog
Last Updated: [2023-03-29 Wed 07:06]
Sometimes you’ll have to pipe something to a file as root. However,
you’ll find you’ll run into issues when running something like this:
sudo echo "" > textfile.txt. Despite
using the sudo command, you’ll get a
permission denied error. This is because only the part of the command
before the > is run through sudo, the
output is being performed as your own user. Most people would get around
this using the dreaded sudo su method.
However, this is a better way:
echo "" | sudo tee textfile.txt > /dev/nullA little explanation is needed here.
Firstly we’re using echo to write
nothing to the stdout. We’re then piping this to sudo which in turn is running tee as root to a file we’ve called
“textfile.txt”. Finally, tee also, by
default, prints what it’s doing back to stdout as it’s intended to push
the same data to two places, so we’re redirecting that to /dev/null to keep the command silent.
The same method can be used to do MySQL dumps to a directory that is only readable by normal users:
sudo mysqldump --routines --single-transaction --quick --max_allowed_packet=1G --database production-data | sudo tee 2021-09-12-production-data-dump-with-routines.sql > /dev/nullIn this example, redirecting tee's
output to /dev/null is absolutely required
it would have happily spat out the full 25GB MySQL Dump to stdout.
DISCLAIMER: The information provided on this website is generated from my own notes and is provided "as is" and without warranties. Robert Ian Hawdon can not be held responsible for damages caused by following a guide published on this site. This website contains links to other third-party websites. Such links are provided as convienice of the reader. I do not endorce the contents of these third party sites.