How to prompt user for sudo password?

前端 未结 1 784
时光取名叫无心
时光取名叫无心 2021-01-25 22:46

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 /

1条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-25 22:51

    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.

    0 讨论(0)
提交回复
热议问题