Delete File in Current Login in Users Library Folder

Mitch260488
New Contributor II

Hi,

What is the best way for a script to delete a folder in the users library for the current logged in user?

Thanks

3 REPLIES 3

jonod2977
New Contributor

Hi,

The easiest way would be something like this:

#!/bin/sh

currentuser=/usr/bin/stat -f%Su /dev/console

rm -rf /Users/$currentuser/pathtofolder

adamcodega
Valued Contributor

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 + "
");'`

dwandro92
Contributor III

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