Skip to main content
Question

Delete File in Current Login in Users Library Folder

  • July 23, 2015
  • 3 replies
  • 2 views

Forum|alt.badge.img+5

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

Forum|alt.badge.img+1
  • New Contributor
  • July 23, 2015

Hi,

The easiest way would be something like this:

#!/bin/sh

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

rm -rf /Users/$currentuser/pathtofolder

acodega
Forum|alt.badge.img+15
  • Valued Contributor
  • July 23, 2015

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

Forum|alt.badge.img+9
  • Contributor
  • July 23, 2015

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