如何提示用户输入sudo密码? [英] How to prompt user for sudo password?

查看:114
本文介绍了如何提示用户输入sudo密码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是,在运行此bash脚本时做出选择后,如何实施要求sudo密码的操作.例如,如果用户选择在/目录中进行搜索,则脚本将以拒绝权限返回.我想弄清楚如何让脚本提示输入密码,然后继续运行.

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

推荐答案

您可以执行以下操作,尽管它有点hacky:

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

基本上$sudo是一个空字符串,除非用户选择1,否则它将运行"sudo".更好的方法是使用第二个if块,如果需要,该块使用sudo运行命令.

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.

这篇关于如何提示用户输入sudo密码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆