Logout hook for emptying trash


I have written a script to delete a specific users trash upon logging out, unfortunately the result is not calculated properly and deletes the trash anyways. Here’s what I have so far:

tell application “Finder”
do shell script “du -ks /Users/student/.Trash”
if result is greater than 50000 then empty trash
end tell

In terminal I can confirm that the trash contents are much lower then 50MB, but the trash deletes anyways. Oddly enough if it’s only a few hundred Kilobytes it will remain in the trash like it supposed to.

Any ideas to what I’m doing wrong?

Model: MacBook
AppleScript: 1.10.7
Browser: Firefox
Operating System: Mac OS X (10.4)

Moving to OS X…


results of do shell script are always text, not a number
In this special case, the result is something like:

2654 /Users/student/.Trash

Try something like this, it avoids the use of the Finder

if (first word of (do shell script "du -ks /Users/student/.Trash") as number) > 50000 then do shell script "rm -r /Users/student/.Trash/*"

Brilliant Stefan. Thank you.

As a (hopefully) interesting technical footnote, when numbers and strings are compared using the <, >, ≤, ≥ operators or their verbal equivalents, Applescript attempts to coerce the item on the right of the operator to the same class as the item on the left before attempting the comparison. Thus, in antnee’s original line:

if result is greater than 50000 then empty trash

. the 50000 was being automatically coerced to text (“50000”) to match the result of the shell script. When the first character of the shell script result was higher than “5”, it would test lexically higher than “50000” even when the text number it began was numerically lower than 50000.

If the test had been done the other way round:

if 50000 is less than result then empty trash

. AppleScript would have attempted to coerce the shell script result to a number. This would have produced an error because the text as a whole can’t be so coerced, but this version would have worked:

if 50000 is less than (word 1 of result) then empty trash

I think, though, in this case, that Stefan’s use of an explicit coercion is to be preferred. :slight_smile: