Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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.

share|improve this question
add comment

2 Answers

up vote 5 down vote accepted

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.

share|improve this answer
add comment

su is available on most unix systems and should work:

su root -c 'echo "add this line to the code" >> fileName'
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.