↑ arvau

Stack Overflow / Bash echo text into sudo file

I am trying to push some text into a file which requires sudo:

sudo echo "some text" > /etc/path/to/file

But I keep getting the following error:

bash: /etc/path/to/file: Permission denied

I can do it with nano, but I kind of need to do it programmatically. Is it a problem with the > operator? Is there a script I can use instead?

Stack Overflow / Bash echo text into sudo file

Shell (bash in this case) does the redirection (>) first before running the command. So /etc/path/to/file will be created before the command with sudo even runs and the normal user does not have sufficient permission to create the file /etc/path/to/file, hence the error message regarding permission.

You can do:

sudo bash -c 'echo "some text" > /etc/path/to/file'

Or use tee:

echo "some text" | sudo tee /etc/path/to/file

Stack Overflow / Bash echo text into sudo file

heemayl already explained the permission issues however you need to take into account that running sudo commands will still require you to enter the user password manually. That is unless you have specified in the sudoers file that the user running sudo doesn't require a password which I hope is not the case.

So in order to avoid entering the password manually you have a couple of possibilities of which almost all are a pretty bad idea since they basically require of you to store your user password outside the regular /etc/shadow file.

The best you could probably do is store your password inside a plain file and heavily restrict access to it with permissions.

echo "password" > ~/.password && chmod 400 ~/.password

After that you can use the -S parameter for sudo to read the password from an external file like this.

sudo -S bash -c 'echo "some text" > /etc/test' <~/.password

Once again, storing user passwords outside /etc/shadow is a huge security risk, especially if the user has sudoer privileges so I would advise against this approach even if it provides some basic protection.