digitaljunkie wrote:
OK
I want to delete the contents of a directory it is the resulting Backups folder below but I want to keep the Folder.
/Users/Shared Items/Backups
Whats the safest way to do this, i.e if it doesn't exist exit my script if it does then delete everything in there.
Also this applies to something else I want to do...
I want to delete a specific file if it exists, if it doesn't I want it to continue with the rest of my script so like this...
rm /Backup/archive.zip
#if file doesn't exist still carry on with my script.
Right on, thanks for the clarification!
Okay, for your file that you want to delete "if it exists" you'll want to use "if" with the "-e" (exists) OR the "-f" (is a file). -e should work fine in this case:
Code:
#!/bin/bash
## Let's make the file name into a variable (Makes it
## easier to adapt this script to other purposes later)
FILE="/Backup/archive.zip"
## Let's check to see if the file exists
if [ -e "$FILE" ]; then
## remove it if it does exist
rm -v $FILE
else
## or say that it doesn't exist
echo "$FILE doesn't exist"
fi
For your original question, removing all the files in a directory, you'll want to do some checks to make sure the script doesn't do anything silly, like rm -rf /* (I once wrote a script that was supposed to put directories in a variable, but I made a typo. the script assumed that since the variable was empty, I meant "/"... it was ugly... almost got fired over it...). There
Code:
#!/bin/bash
## Let's make the directory a variable (Makes it
## easier to adapt this script to other purposes later)
DIR="/Users/Shared Items/Backups"
## Let's make sure that the directory exists
## AND that it's a directory (Probably overkill,
## maybe unnecessary)
if [ -e "$DIR" ] && [ -d "$DIR" ]; then
## remove everything in the directory
for i in `ls "$DIR"`; do
rm -v "$DIR"/"$i"
done
else
## or say that the dir doesn't exist
echo ""$DIR" doesn't exist"
fi
That should do it... I didn't add a check to see if the directory was empty, so if there's nothing there, you get nothing returned... might add that just for the sake of completeness...