Search code examples
linuxbashshellfedora

How to prompt user for sudo password?


My question is how do I implement asking for the sudo password once a selection has been made when running this bash script. Example being if the user selects to search in the / directory the script returns with permission denied. I would like to figure out how to have the script prompt for the password and then continue running.

#!/bin/bash
function press_enter
{
echo ""
echo -n "Press Enter to continue"
read
clear
}
selection=
where_selection=
what_selection=
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 / ; press_enter ;;
2) cd /home ; 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 find . -name "$a" -print -quit | grep -q .
then
echo "You found the file"
else
echo "You haven't found the file"
fi
done

Solution

  • 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.