1

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
jww
  • 97,681
  • 90
  • 411
  • 885
Lilcomet
  • 25
  • 6
  • Also see [Prompt for sudo password and programmatically elevate privilege in bash script?](https://unix.stackexchange.com/q/28791/56041), [How to enter password only once in a bash script needing sudo](https://askubuntu.com/q/711580), [Request root privilege from within a script](https://askubuntu.com/q/746350), [Create a sudo user in script with no prompt for password...](https://stackoverflow.com/q/43853533/608639), [sudo with password in one command line?](https://superuser.com/a/67766/173513), etc. – jww Mar 30 '18 at 17:55

1 Answers1

0

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.

John Moon
  • 924
  • 6
  • 10