Remotely remove .app files from Trash

rpayne
Contributor II

I'm attempting to create a script to remove .app files from User's trash bins. I have the following script that is returning "No such file or directory." 

#!/bin/bash
# for each user in the /Users folder that is (!)not the Shared folder
for dir in /Users/[!Shared]*
do
# Create a variable with just the users name
loggedInUser=$( scutil <<< "show State:/Users/ConsoleUser" | awk '/Name :/ && ! /loginwindow/ { print $3 }' )

# Delete app files from the currect user's trash
rm -R /Users/${loggedInUser}/.Trash/*.app

# For logs or viewing progress--shows when the users trash has been emptied
echo -e ".app files removed from Trash for: ${loggedInUser}"
done

Has anyone done something like this?

6 REPLIES 6

rpayne
Contributor II

The majority of our machines are Sonoma 14.3.

A_Collins
Contributor

It is because your script has wrong logic, you are getting of usernames but you are running same command for all users. Therefore, for first user it is already deleting the "*.app" file, and for all others it would return "No such file or directory" as item is already being delete. You do not need logged in user. 

For better script you can use below

#!/bin/bash
# List of user accounts
ListofUsers=$(dscl . ls /Users | grep -v '_' | grep -v 'root'| grep -v 'daemon' | grep -v 'nobody' | grep -v 'localadmin')
fileExt="*.app"
for trash in $ListofUsers
do
# Delete app files from the currect user's trash
rm -R /Users/${trash}/.Trash/${fileExt}
# For logs or viewing progress--shows when the users trash has been emptied
echo -e "${fileExt} files removed from Trash for: ${trash}"
done

However, you will still receive an "No such file or directory" for any user that does not have *.app

This is not working for me either. I have a .app file in the trash (Webex.app) and I'm still getting "No such file or directory" and the file remains in the trash. It is correctly identifying the user however (as before). 

TarenDoo
New Contributor

Hello, I created a script that can assist with your issue in GitHub.The trash file removal script is designed to remove the files with the extension outlined in the Recycle Script.  Check out the link: https://github.com/TarenDoo83/TRASH-CAN-SCRIPT.

Thank you. I've used almost this exact script and it grabs the management account and the files remain.

rpayne
Contributor II

I think I'm just gonna take the easy way out with a policy and the command payload of "rm -R ~/.Trash/*.app". Thank you everyone.