I need to write a bash script, which checks if a new user logged in within 5 seconds, and if so, print it’s details: name, username, …… I already have the following code, which checks if a new user have logged in:
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
Advertisement
Answer
If I understand the question correctly, you want to find the difference between two Bash variables and keep the difference in a new variable. One possibility is to save the diff result into a variable:
diff_result=`diff -u <(echo "$originalusers") <(echo "$newusers")` echo -e "diff result:n$diff_result"
However, if you use this code you will still have to parse the diff result. Another possibility is to use the comm command:
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"
The first two lines create sorted unique lists of line separated usernames. The comm command is used to find usernames that appear only in the new usernames list.