It often happens that you need to echo or cat something to some config file, or maybe a log, or something else owned by root. It also often happens that you try to run it as a regular user and get a permission denied error. And normally you'd just prepend your command with sudo and be done with it, but output redirects are not that easy: current shell will handle them itself, they will not be passed to sudo and you will still have your permission problem.
Luckily, the fix is easy: instead of prepending the command, you just replace > somefile with | sudo tee somefile and >> somefile with | sudo tee -a somefile whatever the command before was. You may also add > /dev/null if you don't want if to echo everything.
Example:
Of course, this is not the only way and it's not always the best but it works all the time, it's quite straight-forward (doesn't require any escaping or changing the original command in any way), and it doesn't require any additional programs to be installed.
Feel free to write about your preferred method in comments.
And a bonus tip about tee, not sudo-related:
Luckily, the fix is easy: instead of prepending the command, you just replace > somefile with | sudo tee somefile and >> somefile with | sudo tee -a somefile whatever the command before was. You may also add > /dev/null if you don't want if to echo everything.
Example:
echo "truncated" | sudo tee /var/log/toolong.log echo "additional log record" | sudo tee -a /var/log/toolong.log
Of course, this is not the only way and it's not always the best but it works all the time, it's quite straight-forward (doesn't require any escaping or changing the original command in any way), and it doesn't require any additional programs to be installed.
Feel free to write about your preferred method in comments.
And a bonus tip about tee, not sudo-related:
wget -O - http://example.com/dvd.iso \ | tee >(sha1sum > dvd.sha1) \ >(md5sum > dvd.md5) \ > dvd.iso