Looking for Apple script to empty User's Trash

mac4enterprise
New Contributor

I'm trying to create a JAMF policy to enforce the Trash folder to be scanned for files older than 4 days and have those files removed. Does anyone have script than can do something like this?

21 REPLIES 21

mm2270
Legendary Contributor III

Hi, this is possible to do. I'm not clear on the method from Applescript, but most likely it can be done. It can also be done with a simple shell script.
One thing though - I don't know your circumstances for needing to do this, but I kind of cringe at the idea of deleting user's files without their knowledge. You may want to consider popping up a message on screen telling them they have old and/or a large number of files in their Trash and should delete them, rather than doing it without their consent. That's just my personal opinion of course.

perrycj
Contributor III

Yea I agree with @mm2270

Not sure you should just "do it" without letting them know for all the reasons he mentioned. But if you wanted to, you could certainly just use a simple bash script to do so.

jacob_salmela
Contributor II
#!/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
    user=`echo $dir | cut -d'/' -f3`

    # Empty each users trash
    rm -rf $dir/.Trash/*

    # For logs or viewing progress--shows when the users trash has been emptied
    echo -e "Trash has been emptied for:	$user"
done

donmontalvo
Esteemed Contributor III

@mm2270 Yea, this would be more of a user training issue. If the issue is space related, an hourly policy that tosses up a "You are running low on space, please empty your trash and if these prompts don't go away contact Help Desk to prevent any issues" prompt if a user is over 80% should be enough for the user to address the issue.

--
https://donmontalvo.com

mac4enterprise
New Contributor

Appreciate the responses. This is a compliance/corporate policy we are already doing for PC users.

Jacob, thanks for the bash script - I cant tell if this can actually find and delete files in the Trash older than 4 days or if it's more of an all or nothing. I assume you could create a policy to run this script daily, at login, at startup, or during regular checkin cycles??

tlarkin
Honored Contributor

Hi @mac4enterprise,

I hope you are doing well. I am actually working on a presentation I am going to give next month about scripting and advanced work flows with the Casper Suite and came to JAMF Nation for ideas. Stumbled upon this post and sort of whipped up a quick and dirty bash/Applescript that will prompt the user to empty their trash if it is over 1gig in size. It is quite simple and runs locally on my box, but I have not tried it via a policy yet in the JSS. I could probably swap out the Applescript code with JAMF Helper as well, but I already had the yesNo function in my code library so I didn't have to write it again.

So, maybe test this out and see what you think. If the Applescript doesn't work JAMF Helper could, or something like CocoaDialog could as well.

#!/bin/bash


# get the total amount of disk space the current user's trash has

currentUser=$(ls -l /dev/console | awk '{ print $3 }')

trashSpace=$(du -h -c /Users/${currentUser}/.Trash/ | awk '/total/ { print $1 }')

# set the emptry trash message for the end user

question="system maintenance has determined your trash is starting to fill up.  Please select Yes to empty the trash.  WARNING:  This will permanently empty all the contents of the your trash.  Press No to cancel."

# determine if it is Megabytes or Gigabytes

case ${trashSpace} in

  *G ) size='gigs';;
  * ) echo "trash is under 1gig"
esac

# yesNo function

yesNo () {

    # prompt user for yes|no answers

theAnswer=$(/usr/bin/osascript <<AppleScript
tell application "Finder"
 activate
 display dialog "Hello ${currentUser}, ${question}" buttons {"No","Yes"} default button 2
  if the button returned of the result is "No" then
   set theAnswer to No
  end if
end tell
AppleScript)

/bin/echo "${theAnswer}"

if [[ ${theAnswer} == "no" ]]
    then theAnswer="no"
    else theAnswer="yes"
fi
}

# now if the size is in gigs, not matter how many, prompt to empty trash

if [[ ${size} == 'gigs' ]]
  then yesNo
fi

if [[ ${theAnswer} == 'yes' ]]
  then rm -rf /Users/${currentUser}/.Trash/
fi

exit 0

Let me know if this helps at all. I only tested it on my box locally so please test this out and see if it helps.

Thanks,
Tom

mm2270
Legendary Contributor III

We'll, if it's a company policy and you have managements ok to do it, then here's something that'll do it for you. I still don't think this is such a great idea. I could understand it in an edu environment, but since you used the term "corporate policy" I assume you're in a business work setting. Anyway, here's a one liner you could drop into the Run Command field in a policy.

find $(dscl . read /Users/$(ls -l /dev/console | awk '{print $3}') NFSHomeDirectory | awk '{print $NF}')/.Trash -mtime +4 -exec rm -R {} ;

This will locate items older than 4 days in the currently logged in users Trash and delete them.
FWIW, Jacobs script will delete items in the Trash for all accounts on the Mac but it will delete everything, not just ones that are 4 days old or older. I personally think that's kind of a sledgehammer approach, but if you wanted to make sure to delete everything across all accounts, it could work. You could also expand the one liner above into a full script to loop through each local home directory on the Mac and only delete the items that match the 4+ days modification date search.

Please be careful with the above, and test it thoroughly. Since its using rm -R and would be running as a root process, if you mistype this, or something's off with my syntax, it could be very damaging.

TheMacGuys
New Contributor III

Greetings everyone,

I am trying to put in a "First-Aid" Empty Trash button in Self Service. Often users call and for various reasons the trash will not empty. So I wanted to put a very simple button in Self Service to take care of it.

For a long while I had this little command doing the job, but it stopped working for some reason. Simple but it worked.

rm -rf ~/.Trash/*

Of course this command works locally in the Terminal but I can't get it to work any longer as a script via Self Service? Any thoughts?

Thanks

mm2270
Legendary Contributor III

It doesn't work because the tllde "~" expands to the home directory path of the account the command is being run under, which would be your Casper Suite service account, not the user logged into the Mac. You need to get the logged in user's path instead.

If you want to keep it all to one line you could try this-

rm -rf $(dscl . read /Users/$(ls -l /dev/console | awk '{print $3}') NFSHomeDirectory | awk '{print $NF}')/.Trash/*

As I mentioned in previous post above, please test this carefully before actually putting this into production.

arlomiller
New Contributor

I made an automator action that does this and then just have that automator action run at login. this has been working pretty well for me. In my case, I'm just wiping out their downloads, but you could use it to clean up all kinds of things. I've even been threatening to use it to clean their desktops of crap!

It is setup like this:
1. Get specified Finder Items
just specify what folders you want to clean here. Can be anything, and using relative links works

  1. Get Folder contents
    Repeat for each subfolder found is checked

  2. Filter finder items
    In my case, find all files where date last modified is not in the last day
    Note, you can even specify files/folders to exclude, which is kind of awesome!

  3. Move finder items to trash

  4. Run applescript
    on run {input, parameters} tell application "Finder" empty the trash with security
    end tell return input
    end run

jacob_salmela
Contributor II

I have used this as a Self Service item for quite a while. Any of the solutions mentioned will work; this is just another option.

#!/bin/bash
# Variable to hold the value of the current user
currentuser=$(stat -f "%Su" /dev/console)

# Force empty the trash of the currently logged in user
su "$currentuser" -c "rm -rf ~/.Trash/*"

donmontalvo
Esteemed Contributor III

rm -Rf /Users/$3/.Trash/*

https://jamfnation.jamfsoftware.com/article.html?id=146

Note: When executed as a login or logout policy, the "$3" variable receives user information for the user logging in or out. When executed through Self Service, it receives the username of the account used to log into Self Service. Any other method of execution will fail to pass the correct user information.
--
https://donmontalvo.com

mm2270
Legendary Contributor III

Yeah, that might work. I've had very mixed success in relying on $3 in policies and tend to get the logged in user using other methods myself. Besides, it makes commands/scripts a bit more portable if you decide to use it outside of something like Self Service or a login/logout triggered policy.

donmontalvo
Esteemed Contributor III

We've always put the command here, rather than using a script:

Edit Policy > Advanced > Files & Processes > Run Command:

--
https://donmontalvo.com

TheMacGuys
New Contributor III

Thanks everyone for the great ideas, I can't express enough how valuable it is to have all of you to turn to for ideas.

It is working. I used the Bash command line option which is similar to what I have been doing. I never caught the ~, I wasn't thinking. Of course it is not running as the user...argh! Good catch.

PS....I love the idea of dumping all the junk off their desktop but that wouldn't go over well. LOL

donmontalvo
Esteemed Contributor III

Feel free to "Mark as answer" for the posts that helped. :)

--
https://donmontalvo.com

TheMacGuys
New Contributor III

I would love to. (-; How do I do that?

donmontalvo
Esteemed Contributor III

Sorry that was meant for @mac4enterprise, the original poster. :)

--
https://donmontalvo.com

donmontalvo
Esteemed Contributor III

@mm2270 For some reason the short command doesn't work on our 10.9.2 test Macs, but yours does (yay!). We added an unlock command to the beginning of your command, works like a charm. :)

chflags -R nouchg $(dscl . read /Users/$(ls -l /dev/console | awk '{print $3}') NFSHomeDirectory | awk '{print $NF}')/.Trash/*; rm -rf $(dscl . read /Users/$(ls -l /dev/console | awk '{print $3}') NFSHomeDirectory | awk '{print $NF}')/.Trash/*
--
https://donmontalvo.com

MST
Contributor

Sorry to interrupt this post, I am looking for something similar but to emty (delete all files and folders) from a desktop. Thank You -MST

bentoms
Release Candidate Programs Tester

@MST something like the below should work:

do shell script "rm -rf ~/Desktop/*"

That's if run by the user who's desktop it is.