我的家庭作业要求我
- 用户在其主目录中存储了太多文件,您希望通知前 5 个违规者。您可能希望为更多或更少的用户再次运行此脚本,因此此选择将提示需要识别的用户数量,检查他们的主目录中有多少文件,并将这些用户的列表发送到标准输出。
这是到目前为止我所掌握的第一部分内容;我只是无法弄清楚#5。
echo " Please enter file name: "
read workingfile
while true
do
echo "1) Check who is logged into the system and pull up contact information"
echo "2) Check who has left a system process running and stop it"
echo "3) Check if two users have the same userid, and prompt to change it"
echo "4) Get a list of all users on file and list information about them"
echo "5) List the top 5 users that have to many files in their home directory and list them"
echo " "
echo -n "Choice: "
read choice
case "$choice" in
1)
user=$(who | cut -d' ' -f1 | sort | uniq)
grep "$user" $workingfile | sed 's/\:/ /g' | sed 's/stu[0-9]*//g'
break
;;
2)
echo "Please enter a username: "
read user
echo $user
ps -u $user
echo "Would you like to end the proccess for $user ? (yes or no)"
read choice2
if [ $choice2 = "yes" ];
echo "killall -u USERNAME.” break
else
echo "We will not be stopping any background proccesses!"
break
exit
fi
;;
3)
sed -i '0,/stu5/{s/stu5/stu6/}' myuser.txt
sed -i '0,/stu5/{s/stu5/stu4/}' myuser.txt
echo "Testing if a user has the same id"
if [[ $(grep -o "stu[0-9]" $workingfile | uniq -d) != 0 ]]; then
result=$(grep -o "stu[0-9]" $workingfile | uniq -d)
echo " We will be replacing the first instance of $result please input what number you'd like to replace it with!: "
read input
echo "replacing id..."
sed -i '0,/stu5/{s/stu5/stu4/}' $workingfile
cat $workingfile
break
else
echo " There is no result!"
break
exit
fi
;;
4) echo "List of all users in file: "
cat $workingfile | sed 's/\:/ /g' | sed 's/stu[0-9]*//g'
break
;;
答案1
首先,您必须做出一个假设,要么getent passwd
实际返回所有有效用户(在某些情况下不会),要么所有用户的主目录都遵循该形式/home/username
(这也不是一个很好的假设)。让我们继续第二个假设。然后你可以尝试类似的事情
cd /home
for user in *; do printf "%s\t%s\n" $(find $user -type f | wc -l) $user; done | sort -rn > /tmp/sort.$$
for user in $(head -5 /tmp/sort.$$ | cut -f2); do notify $user; done
您刚刚又做了两个假设。如果用户的文件名称中包含回车符,则计数将关闭。另外,我假设notify
这里的命令是某种电子邮件,并且还假设用户的电子邮件与其用户名相同。也许是一个很好的假设,但也并不总是正确的。