Bash Shell脚本无限循环登录脚本

时间:2015-10-04 21:53:56

标签: sh infinite-loop login-script

目前正在尝试编写脚本以显示网络上的用户登录和注销。目前的代码如下:

echo "The current users are:"

who | awk '{print $1}' | sort > tempfile1
cp tempfile1 tempfile2
more tempfile1

while true
do
    who | awk '{print $1}' | sort > temp2
    cmp -s tempfile1 tempfile2

    case "$?" in

    0)
            echo "No user has logged in/out in the last 3 seconds."
            ;;

    1)
            user=`comm -23 tempfile1 tempfile2`
            file=`grep $user tempfile1 tempfile2 | cut -c 1-5`

            [ $file == "tempfile1" ]
                    echo "User "$user" has logged out."


            [ $file == "tempfile2" ];
                    echo "User "$user" has logged in."

            ;;
    esac
    rm tempfile1
    mv tempfile2 tempfile1
    sleep 3

done

运行脚本我得到以下内容:

The current users are:
No user has logged in/out in the last 3 seconds.
mv: cannot stat ‘tempfile2’: No such file or directory
rm: cannot remove ‘tempfile1’: No such file or directory
mv: cannot stat ‘tempfile2’: No such file or directory

我相当确定此代码中存在语法问题,但我是盲目的。与其他类似脚本的类似例子相比无济于事。如果有人可以帮助指出我有多少白痴,那将是非常有帮助的。干杯。

1 个答案:

答案 0 :(得分:2)

在第一次循环结束时,您rm tempfile1然后mv tempfile2。当你回到循环顶部并执行cmp时,你没有这两个文件。

who | awk '{print $1}' | sort > temp2应该是who | awk '{print $1}' | sort > tempfile2吗? (temp2在任何其他地方都不会被引用...)

相关问题