Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append to protected file

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?

like image 832
Richard Avatar asked May 22 '12 08:05

Richard


People also ask

How do I append with Sudo?

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.

How do you append to a file in Shell?

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>.

How do I append a message to a file without a newline character?

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.


2 Answers

echo "Append string" | sudo tee -a protected_file >/dev/null
like image 170
Dennis Williamson Avatar answered Nov 05 '22 09:11

Dennis Williamson


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.

like image 41
Amadan Avatar answered Nov 05 '22 09:11

Amadan