2015-10-04 180 views
0

当前尝试编写脚本以显示用户登录和注销网络。当前的代码如下:Bash Shell脚本无限循环登录脚本

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 

我相当肯定有这个代码中的语法问题的地方,但我是个盲人。与其他相似的这种脚本类似的例子无济于事。如果有人能帮忙指出我是多么的白痴,那将是超级有用的。干杯。

回答

2

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

who | awk '{print $1}' | sort > temp2应该是who | awk '{print $1}' | sort > tempfile2? (temp2从来没有引用其他地方...)

+0

我血腥的知道,我犯了一个愚蠢的错误哈哈。感谢您指出。 – JJ1