gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 12:15:36 24 4
gpt4 key购买 nike

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

#!/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 block ,在需要时使用 sudo 运行命令。

关于linux - 如何提示用户输入 sudo 密码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47538572/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com