2015-10-04 186 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