2017-05-06 27 views
1

我需要編寫一個bash腳本,它檢查一個新用戶是否在5秒內登錄,如果是,打印它的詳細信息:名稱,用戶名...... 我已經有了下面的代碼,它檢查如果新用戶已經登錄:如何保存來自兩個變量的更改?

originalusers=$(users) 
sleep 5 
newusers=$(users) 
if diff -u <(echo "$originalusers") <(echo "$newusers") 
then 
echo "Nothing's changed" 
exit 1 
else echo "New user is logged in" 
diff -u <(echo "$originalusers") <(echo "$newusers") >shell 

回答

0

如果我正確地理解了這個問題,您想要找出兩個Bash變量之間的差異並將差異保留在新變量中。一種可能性是將差異結果保存到一個變量:

diff_result=`diff -u <(echo "$originalusers") <(echo "$newusers")` 
echo -e "diff result:\n$diff_result" 

但是,如果您使用此代碼,你仍然必須解析差異的結果。另一種可能性是使用comm命令:

originalusers_lines=`sed -e 's/ /\n/g' <(echo "$originalusers") | sort -u` 
newusers_lines=`sed -e 's/ /\n/g' <(echo "$newusers") | sort -u` 
comm_result=`comm -13 <(echo "$originalusers_lines") <(echo "$newusers_lines")` 
echo -e "new users:\n$comm_result" 

前兩行創建排序的唯一行分隔用戶名列表。 comm命令用於查找僅出現在新用戶名列表中的用戶名。

+0

謝謝veryyyy多!!!!!它正在工作!!!!! :DDDDD –

0

這裏是一個。這是一個bash腳本,它使用awk來計算出口和入口。

$ cat script.sh 
#!/bin/bash 
read -d '' awkscript <<EOF # awk script is stored to a variable 
BEGIN{ 
    split(now,n) 
    split(then,t) 
    for(i in n) 
     a[n[i]]++ 
    for(j in t) 
     a[t[j]]-- 
    for(i in a) 
     if(a[i]) 
      print i, (a[i]>0?"+":"") a[i] " sessions" 
} 
EOF 
while true     # loop forever 
do 
    sleep 1     # edit wait time to your liking 
    then="$now" 
    now="$(users)" 
    awk -v then="$then" -v now="$now" "$awkscript" 
done 

運行:

$ bash script.sh 
james 14 sessions # initial amount of my xterms etc. 
james +1 sessions # opened one more xterm 
james -1 sessions # closed one xterm 

真的沒有任何地方有很多用戶來來往往的測試它。

相關問題