如何提示用户输入 sudo 密码?

How to prompt user for sudo password?

我的问题是,当 运行 这个 bash 脚本做出选择后,我如何实现要求 sudo 密码。例如,如果用户选择在 / 目录中搜索脚本 returns,但权限被拒绝。我想弄清楚如何让脚本提示输入密码,然后继续 运行。

#!/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

你可以做这样的事情,虽然有点 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

基本上$sudo是一个空字符串,除非用户选择1,那么它将运行 "sudo"。更好的方法是使用第二个 if 块 运行 在需要时使用 sudo 命令。