user3092768
user3092768

Reputation: 13

Need help to make Mac .sh script in order to remove Recovered files in Trash

I was trying to make a mac sh script in order to remove "Recovered files" folder created by Logitech's mouse software in Trash.

When I input ls ~/.Trash/Recovered\ files, I got these in Terminal:

com.logitech.gkeysdk.501    com.logitech.lcdmon.501

I would like to make this script to remove the "Recovered files" folder in this way:

If detects only these two files (com.logitech*) in "Recovered files", then remove "Recovered files".

Else, do not remove the folder.

So I made a script like this:

EXPECTED="com.logitech.gkeysdk.501  com.logitech.lcdmon.501"
lslogitech=$(ls ~/.Trash/Recovered\ files)

export print=$(lslogitech)
echo "print=$print"

if [ $(print) = "EXPECTED"]; then
  echo "Delete Recovered files in Trash"
  rm -rf ~/.Trash/Recovered\ files*
else
  echo "There are other files in Recovered files"
fi

But it doesn't work. It's my first time to write this thing. Any help would be appreciative!

Upvotes: 1

Views: 412

Answers (1)

Donovan
Donovan

Reputation: 15917

This is probably more along the lines you want:

EXPECTED="com.logitech.gkeysdk.501  com.logitech.lcdmon.501"
lslogitech=$(ls ~/.Trash/Recovered\ files)

for TRASH_FILE in $lslogitech ; do
    for EXP_FILE in $EXPECTED ; do
        if [ "$TRASH_FILE" == "$EXP_FILE" ] ; then
            rm -f ~/.Trash/Recovered\ files/$TRASH_FILE
        fi
    done
done

rmdir ~/.Trash/Recovered\ files &> /dev/null || echo "There are other files in Recovered files"

This loops through your ~/.Trash/Recovered\ files directory and removes any files listed in the EXPECTED list. It then attempts to silently remove the directory and issues the echo only if it fails.

OR, more concisely:

EXPECTED="com.logitech.gkeysdk.501  com.logitech.lcdmon.501"
TRASH_DIR="~/.Trash/Recovered\ files"

for TRASH_FILE in $(eval ls "$TRASH_DIR") ; do
    for EXP_FILE in $EXPECTED ; do
        [ "$TRASH_FILE" == "$EXP_FILE" ] && eval rm -f $TRASH_DIR/$TRASH_FILE
    done
done

eval rmdir $TRASH_DIR &> /dev/null || echo "There are other files in $TRASH_DIR"

Note: The eval is needed to expand ~ into your home directory path name

UPDATE: This solution adds a search for multiple .Trash directories

EXPECTED="com.logitech.gkeysdk.501  com.logitech.lcdmon.501"

ls -d ~/.Trash/Recovered\ files* | while read TRASH_DIR ; do
    for TRASH_FILE in $(ls "$TRASH_DIR") ; do
        for EXP_FILE in $EXPECTED ; do
            [ "$TRASH_FILE" == "$EXP_FILE" ] && rm -f "$TRASH_DIR"/"$TRASH_FILE"
        done
    done
    rmdir "$TRASH_DIR" &> /dev/null || echo "There are other files in $TRASH_DIR"
done

Upvotes: 2

Related Questions