How to add a line to a file which has only root write permission and to continue the script execution
Solution 1
There's a tip in the sudo
man page which explains how to do something like this. Here's my one-liner:
#!/usr/bin/bash
sudo sh -c "echo \"add this line to the code\" >> fileName"
Obviously, you'll first have to set up your user to have sudo
privileges. The sh
shell is used because of the redirection to the root-owned file. I also had to escape the quotes used for the echo
command.
Solution 2
su
is available on most unix systems and should work:
su root -c 'echo "add this line to the code" >> fileName'
Solution 3
You could use tee
with sudo
:
echo "add this line to the code" | sudo tee -a filename > /dev/null
echo
's output is redirected with |
(pipe) to sudo tee
.
tee
reads from standard input and writes to standard output any given file, in this case filename
. -a
(or --append
) makes tee
append to files, without it the files would be overwritten.
As tee
is run with sudo
it opens files with root-permissions. Finally, > /dev/null
suppresses tee
's output to standard output.
One advantage of using tee
instead of just starting the whole command including redirection with su -c
or sudo sh -c
is, that you do not have to change the quoting of the initial command in any way (Quoting lines already containing quotes can get quite ugly at times).
Related videos on Youtube
Alex
Updated on September 18, 2022Comments
-
Alex almost 2 years
I am trying to learn bash scripting. I am working on a practical problem and at one point I need to add a line to a file which requires
root
permission to write.The code looks like this:
# some code echo "add this line to the code" >> fileName # some code
Is it possible to somehow make the script ask for the root password, validate the password, and on successful authentication modify the file? The script should then return to the user mode and continue the command execution.
-
Adaephon about 10 yearsWhy
ssh
? You do not needsu
withsudo
and neither do you need to specifyroot
as it is the default. All in all, a bit more explanations would be nice as the OP wanted to learn something and not just a problem solved. -
Ryne Everett over 9 yearsUnlike with
sudo
, passwords don't seem to get cached withsu
. -
miracle173 over 9 years@Ryne Everett: I am not familiar with sudo. But the behaviour of 'su' is actually as needed by the script of the OP. Most of the time I use 'su' the other way round: changing from root to another user. In this case no password is needed ast all.
-
miracle173 over 9 yearsI think you will run into troubles with you double quotes