我正在尝试编写一个shell脚本,在其中我接受来自用户的用户名,并检查系统中是否存在该特定用户。如果是,那么更改密码,否则会显示一个错误。在这个阶段,我只是检查输入的用户名是否存在,并相应地显示一条消息。
这是我写的代码:
#!/bin/bash
echo "Enter the username whose password needs to be reset: "
read UNAME
echo "You want to reset password for $uname"
awk -F':' '{print $1}' /etc/passwd > userlist.txt
FLAG = 0
for LINE in $(cat userlist.txt)
do
if [ "$UNAME" == "$LINE" ]
then
FLAG = 1
break
else
FLAG = 0
fi
done
if[ "$FLAG" == 0 ]
then
echo "User $UNAME does not exist"
else
echo "Password for $UNAME can be reset"
fi这里的问题是,由于某种原因,bash将我的FLAG变量作为命令处理。
这是输出:
Enter the username whose password needs to be reset:
abc
You want to reset password for
./chpwd.sh: line 9: FLAG: command not found
./chpwd.sh: line 18: FLAG: command not found
./chpwd.sh: line 18: FLAG: command not found
./chpwd.sh: line 18: FLAG: command not found
./chpwd.sh: line 18: FLAG: command not found
./chpwd.sh: line 18: FLAG: command not found
./chpwd.sh: line 18: FLAG: command not found
./chpwd.sh: line 18: FLAG: command not found
./chpwd.sh: line 18: FLAG: command not found
./chpwd.sh: line 18: FLAG: command not found
./chpwd.sh: line 18: FLAG: command not found
./chpwd.sh: line 18: FLAG: command not found
./chpwd.sh: line 18: FLAG: command not found
./chpwd.sh: line 18: FLAG: command not found
./chpwd.sh: line 18: FLAG: command not found
./chpwd.sh: line 18: FLAG: command not found
./chpwd.sh: line 18: FLAG: command not found
./chpwd.sh: line 18: FLAG: command not found
./chpwd.sh: line 18: FLAG: command not found
./chpwd.sh: line 18: FLAG: command not found
./chpwd.sh: line 18: FLAG: command not found
./chpwd.sh: line 18: FLAG: command not found
./chpwd.sh: line 18: FLAG: command not found
./chpwd.sh: line 18: FLAG: command not found
./chpwd.sh: line 18: FLAG: command not found
./chpwd.sh: line 18: FLAG: command not found
./chpwd.sh: line 18: FLAG: command not found
./chpwd.sh: line 18: FLAG: command not found
./chpwd.sh: line 18: FLAG: command not found
./chpwd.sh: line 18: FLAG: command not found
./chpwd.sh: line 18: FLAG: command not found
./chpwd.sh: line 18: FLAG: command not found
./chpwd.sh: line 18: FLAG: command not found
Password for abc can be reset正如你们所看到的,它挂在FLAG变量上。我不知道为什么!
发布于 2015-02-27 12:20:44
shell中的变量是用语法var=value (或者更好的var="value")设置的。也就是说,您不能在=周围有空格。这就是为什么你的剧本在抱怨:
FLAG = 0是这样说的:使用参数FLAG和0运行命令=。
所以你想写的是:
FLAG=0另外:注释读取文件可以改进。发自:
for LINE in $(cat userlist.txt)
do
...
done至
while IFS= read LINE
do
...
done < userlist.txt其他事情:
if[ "$FLAG" == 0 ]需要[和]周围的空间
if [ "$FLAG" == 0 ]实际上,如果要进行整数比较,则必须使用-eq来查看值是否相同:
if [ "$FLAG" -eq 0 ]发布于 2015-02-27 12:41:57
您可以使用简单的脚本查找特定的用户名是否存在。
#!/bin/bash
Read -p "enter ur username" uid
Grep ^$uid /etc/passwd
[ $? != 0 ] && eche -e "/033[31m i can see ur user!" || echo -e "/033[33m u can chang pass "加上,您可以在读/etc/passwd时使用:
Read -p "enter uid for check " uid
IFS=":"
While read UID REST
do
[ $UID -eq $uid ] && echo " user found you can change pass " break
Done </etc/passwdhttps://stackoverflow.com/questions/28764886
复制相似问题