我正在创建一个循环,从文件中获取输入以确定是否允许用户使用特定程序。
#!/bin/bash
boole=false
echo "Username: "
read username
echo "debug0"
for((line=1; $boole=false; line++)); do
echo "debug.5"
auth=`head -n $line users | tail -n $line`
echo "debug1"
if [ $username = $auth ]; then
echo "debug2"
echo "authentication success"
read
exit 0
fi
if [ $auth = "#end" ]; then
echo "debug3"
echo "authentication failed"
read
exit 0
fi
done
echo "skip everything"
输出
Username:
admin
debug0
skip everything
用户的文件
root
admin
...
#end
#end
和boole
应告诉循环结束
这只是调试阶段,所以它实际上并没有执行任何程序,它只是想告诉我是否允许用户使用它。
答案 0 :(得分:0)
bash中的循环不像C循环。基本语法是:
for arg in [list]
do
[command(s)...]
done
然而,有一种类似你正在使用的C风格语法:
for ((x=1; x<=3; x++))
{
echo $x
}
正如评论中所提到的,当您在双括号内写$boole=false
时,{<1}}在之前取消引用,处理双括号的内容,从而成为{{ 1}}。此外,当您将内容括在双括号中时,应使用$boole
进行比较。在任何情况下,无论是false=false
还是==
,它们都会成功,因为第一个成功地将$boole=false
分配给$boole==false
,而第二个是真的,因为false
是真的。
无论如何,在你的情况下,我可能会使用while循环。这是一个例子:
false
答案 1 :(得分:0)
在读取文件时使用while循环,而不是for循环。这在http://mywiki.wooledge.org/BashFAQ/001
中有记录while read -r line; do
something_with "$line"
done
在这种情况下,您可以使用关联数组来存储授权用户列表:
declare -A authorized_users=()
while read -r username; do
authorized_users[$username]=1
done <input_file
...然后您可以检查用户是否在该列表中:
if [[ ${authorized_users[$possible_username]} ]]; then
echo "User is authorized!"
fi
请注意,在bash 4中添加了关联数组语法。
答案 2 :(得分:0)
我试图为你清理它..你可能希望看一些逻辑,因为如果它的任何其他用户它只会返回最后一个跳过所有..无论如何......
有问题要问,因为如果你是在循环输入,那么在你要退出的for循环中它将结束输入不确定你想要实现的是什么,因为它只是使用for循环has是用户作为空格分隔列表输入用户的第一个输出 - 它不是为了继续向用户返回提示...
所以我已经更新了脚本以循环并询问用户输入是否与失败列表匹配:
(对不起,如果它现在已经过了你想要的东西 - 我想它可能更符合你想要的?)
#!/bin/bash
echo "debug0"
i=0;
#Maybe you want something to measure bad input
# right now only if user puts in #end 3 times will this pass
# so again look at the logics if needed add the attempts++ to skip everything..
max_attempts=3;
# current running attempts set as 0;
attempts=0;
#start function repeats for user input
function start() {
echo "Username: "
read input
# run process input function
process_input
}
# The process input function works out what user has put in
function process_input() {
# Go through for loop of users command
loggedin=$(users);
for auth in ${loggedin[@]}; do
echo "debug.5"
echo "debug1"
# if current value from users output matches the user input
if [[ $auth == $input ]]; then
echo "debug2"
echo "authentication success"
#unsure what you are reading here since your not asking for a prompt
read;
exit 0;
# either if input matches #end or anything after 3 attempts that
# does not match admin
elif [[ $auth == "#end" ]] || [[ $attempts -gt $max_attempts ]]; then
echo "debug3"
echo "authentication failed - failed attempts $attempts "
((attempts++))
start;
fi
done
echo "skip everything"
# removed comment from start function below if you want to get user to re-enter
start;
}
# begin your program by running the start function
start;