I want to do something along the lines of:
echo "Append string" >> protected_file
However, as this file is write protected I get an error. Running:
sudo echo "Append string" >> protected_file
seems to run sudo on the echo command, and still gives me the permission error, how do I append to this file?
There are various ways to append a text or data to a file when using sudo command on Linux or Unix. You can use the tee command that opies input to standard output. Another option is to pass shell itself to the sudo command.
You can use cat with redirection to append a file to another file. You do this by using the append redirection symbol, ``>>''. To append one file to the end of another, type cat, the file you want to append, then >>, then the file you want to append to, and press <Enter>.
Assuming that the file does not already end in a newline and you simply want to append some more text without adding one, you can use the -n argument, e.g. However, some UNIX systems do not provide this option; if that is the case you can use printf , e.g. Do not print the trailing newline character.
echo "Append string" | sudo tee -a protected_file >/dev/null
For a literal answer,
sudo sh -c 'echo "Append string" >> protected_file'
But I agree with ShivanRaptor in principle.
Explanation: >>
is a shell operator. If you invoke sudo command
, you do not run another shell; thus you cannot redirect echo
without also redirecting sudo
(which, ultimately, gives you the wrong user id when doing the redirection). The trick is to launch a separate shell inside sudo
, where you can issue the redirection operator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With