First, never use echo password | ...
. on the command line. This is insecure as the password would remain in the history file, plus other users can see the password using the ps
command. If you want to execute a sudo
command without entering a password you can use the NOPASSWD
option in /etc/sudoers
. Check this: https://unix.stackexchange.com/questions/18830/how-to-run-a-specific-program-as-root-without-a-password-prompt
About the permission problem. You are right, the problem is the output redirection >
. You need to know that the shell will open the output file, not the command running with sudo
.
In this example:
sudo command > output.file
the shell tries to open output.file
, then starts sudo command
and set it's standard output to the open file. However, the shell does not have root permissions.
A workaround could be to use the tee
command, like this:
command | sudo tee output.file
however, I would simply grant proper permissions to edit that file. On example way could be to create a group, change the group ownership of that file and you into that group. For example:
# Add group
sudo groupadd developers
# Change group ownership of the file
sudo chown root:developers output.file
# make the file writable by the group
sudo chmod g+w output.file
# Finally put you into that group
sudo usermod -a -G developers YOU
But if you are an admistrative user, meaning you can execute every command with sudo
, the tee
solution above is good enough.