Create a Sudo User in Script with No Prompt for Password, Change to User Without Interrupting Script

How to prompt user for sudo password?

You could do something like this, though it is a little bit hacky:

#!/bin/bash
function press_enter
{
echo ""
echo -n "Press Enter to continue"
read
clear
}
selection=
where_selection=
what_selection=
sudo=""
until [ "$selection" = "3" ]; do
echo -e "Where would you like to search
1- Root
2- Home
3- Exit

Enter your choice ---> \c"
read selection
case $selection in
1) cd / ; sudo="sudo"; press_enter ;;
2) cd /home ; sudo=""; press_enter ;;
3) echo "Have a great day!" ; exit ;;
esac
echo "What is the name of the file you would like to search for?"
read -r a
if $sudo find . -name "$a" -print -quit | grep -q .
then
echo "You found the file"
else
echo "You haven't found the file"
fi
done

Basically $sudo is an empty string unless the user selects 1, then it will run "sudo". A better way to do this would be to have a second if block that runs the command with sudo if needed.

How to get a password from a shell script without echoing

Here is another way to do it:

#!/bin/bash
# Read Password
echo -n Password:
read -s password
echo
# Run Command
echo $password

The read -s will turn off echo for you. Just replace the echo on the last line with the command you want to run.

How do I use su to execute the rest of the bash script as that user?

The trick is to use "sudo" command instead of "su"

You may need to add this

username1 ALL=(username2) NOPASSWD: /path/to/svn

to your /etc/sudoers file

and change your script to:

sudo -u username2 -H sh -c "cd /home/$USERNAME/$PROJECT; svn update" 

Where username2 is the user you want to run the SVN command as and username1 is the user running the script.

If you need multiple users to run this script, use a %groupname instead of the username1



Related Topics



Leave a reply



Submit