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