Posted on 07-23-2015 02:52 AM
Hi,
What is the best way for a script to delete a folder in the users library for the current logged in user?
Thanks
Posted on 07-23-2015 04:12 AM
Hi,
The easiest way would be something like this:
#!/bin/sh
currentuser=/usr/bin/stat -f%Su /dev/console
rm -rf /Users/$currentuser/pathtofolder
Posted on 07-23-2015 05:27 AM
There's another method which is Apple approved and one you want to use especially if you enable fast user switching.
currentuser=`python -c 'from SystemConfiguration import SCDynamicStoreCopyConsoleUser; import sys; username = (SCDynamicStoreCopyConsoleUser(None, None, None) or [None])[0]; username = [username,""][username in [u"loginwindow", None, u""]]; sys.stdout.write(username + "
");'`
Posted on 07-23-2015 05:34 AM
Here is how I would do it:
#!/bin/bash
# Get current logged in user
targetUser=`who | grep console | awk '{ print $1 }'`
# If a user is logged in
if [ -n "$targetUser" ]; then
# Set target directory
targetDir="/Users/$targetUser/Library/Example"
# If target directory exists, output information and remove the directory
[ -d "$targetDir" ] && { echo "Removing "$targetDir"..."; rm -Rf "$targetDir"; }
# If a user is not logged in
else
# Output information
echo "No user is currently logged in"
fi