If you’re writing scripts for macOS management, it is inevitable that you’ll need to delete something. Maybe you generated a temp folder or maybe deletion is the entire purpose of the script.
Here is a trick to avoid nasty accidents with your rm
commands. This should work in bash or zsh:
#!/bin/zsh
function rm_if_exists()
{
#Only rm something if the variable has a value and the thing exists!
if [ -n "${1}" ] && [ -e "${1}" ];then
rm -r "${1}"
fi
}
rm_if_exists $fileToBeDeleted
This simple function tests to see whether path given is a defined variable, and that it actually exists, prior to deleting it. If the given path isn’t defined or doesn’t exist, it won’t process the rm -r
command.
If you want a more verbose output, you can add an else statement:
#!/bin/zsh
function rm_if_exists()
{
#Only rm something if the variable has a value and the thing exists!
if [ -n "${1}" ] && [ -e "${1}" ];then
rm -r "${1}"
else
echo "File doesn't exist: ${1}"
fi
}
rm_if_exists $fileToBeDeleted
Other Methods
Another method to accomplish the same goal is to use variable expansion. Using variable expansion you can cause your entire script to exit if you have a faulty variable (which might be great if you’re scripting the deletion of data.)
These methods are more advanced, and better explained by folks smarter than me. See this great blog post by Stefan Judis where they cover it: https://www.stefanjudis.com/today-i-learned/how-parameter-expansion-helps-to-not-delete-everything/