Simple remove folder script question please?

TechSpecialist
Contributor

Hi All,

I'm creating a button in Self Service that, once pressed it will remove certain files/folders. with the rm and rm -r (for folders) commands.

This works as expected. However, if the folders are already removed and users would press that button again, then Self Service shows an error (obviously because it couldn't execute the command as there was nothing to delete).

I'm not a huge terminal command guru, so could any of you clever clogs improve my 'script' so it never shows an error and stop my users from reporting "Self service is showing an error when I press the button"?

I'm sure it is an easy fix...

1 ACCEPTED SOLUTION

PaulHazelden
Valued Contributor

Try something like this...

if [ -e "/Path/to/Folder" ]
then
echo "Folder exists proceeding with the removal"
# Folder exists remove it
rm -r "/Path/to/Folder"
fi

The -e is looking for the folder existing, if you put !-e it would look for the folder not existing.
To Test it out I would put # in front of the rm and let the echo tell you if it is working, once you are happy you can get rid of the echo and the # from the rm.

View solution in original post

5 REPLIES 5

PaulHazelden
Valued Contributor

Try something like this...

if [ -e "/Path/to/Folder" ]
then
echo "Folder exists proceeding with the removal"
# Folder exists remove it
rm -r "/Path/to/Folder"
fi

The -e is looking for the folder existing, if you put !-e it would look for the folder not existing.
To Test it out I would put # in front of the rm and let the echo tell you if it is working, once you are happy you can get rid of the echo and the # from the rm.

TechSpecialist
Contributor

I knew it was that simple...

Thanks so much!

I love this community...

PaulHazelden
Valued Contributor

You are welcome.

As with most things, test it several times before you make it live. I put the " " around the Path to the folder, this is to trap for any spaces or special characters in the folder name. This is really important if you are using a variable for the folder name, you could rm something you don't want to if you miss this out. I know, I have done it, I managed to bin the contents of the Users folder on 200 Macs, all because I missed out the " " around a variable.

teodle
Contributor II

Oh my. What was the fallout and how did you recover the user data?

I managed to bin the contents of the Users folder on 200 Macs

PaulHazelden
Valued Contributor

@teodle

It was right near the start of term, so there was not much important data lost. But it taught me to test, test and test again everything. The bit that really annoyed me was the 300Gb of loops etc from Komplete and Ableton Live that was in the Shared folder, had to re install that lot on 40 of the Macs.