How to insert message right into an origin - possessed documents making use of sudo?
Redirecting stdout to a file you don't have write permission on
Running a command like
sudo echo 'text' >> /file.txt falls short with:
bash: /file.txt: Permission denied
You are informing bash to open a documents and also add the result of the command
sudo echo 'text' to it, which certainly does not function given that your bash runs as non - origin. Interactively, I generally run
sudo -s to navigate this (ever since the covering runs as origin and also can open the documents). Conversely, you can run
sudo sh -c "echo 'text' >> /file.txt", which additionally functions, yet is a little a problem with all the interpolation/escaping that can conflict if you have actually made complex expressions.
This does not function due to the fact that the redirection is implemented by the covering, not by the command it relates to. Yet your covering is not running as origin, just
echo 'text' is.
An usual method when you require to have origin permissions to contact a documents, yet not to create the information, is to make use of
echo 'text' | sudo tee -a /file.txt
tee publishes the message to stdout, also. In order to silence it so it acts extra comparable to shell appending (
>>), course the stdout to
echo 'text' | sudo tee -a /file.txt > /dev/null
If you do require origin permissions to create the information, you can run 2 different
sudo commands, or run a covering inside
sudo and also do the redirection there (mindful with the pricing estimate).
sudo echo 'text' | sudo tee -a /file.txt sudo sh -c 'echo "text" >>/file.txt'
When overwriting as opposed to adding, if you are made use of to your covering rejecting to trim an existing documents with the
> driver (
set -o noclobber), bear in mind that this defense will certainly not use.
sudo sh -c 'echo >/etc/passwd' and also
sudo tee /etc/passwd will certainly overwrite
/etc/passwd, you would certainly require
sudo sh -o noclobber -c 'echo >/etc/passwd' for that
noclobber readying to additionally be related to the
sh begun by