Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash echo text into sudo file

Tags:

file

bash

sudo

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?

like image 733
PJSCopeland Avatar asked Jul 25 '26 19:07

PJSCopeland


1 Answers

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
like image 61
heemayl Avatar answered Jul 28 '26 16:07

heemayl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!