In a script I'm working on, I want to rm -rf
a folder hierarchy. But before doing so, I want to make sure the process can complete successfully. So, this is the approach I came up with:
#!/bin/bash
set -o nounset
set -o errexit
BASE=$1
# Check if we can delete the target base folder
echo -n "Testing write permissions in $BASE..."
if ! find $BASE \( -exec test -w {} \; -o \( -exec echo {} \; -quit \) \) | xargs -I {} bash -c "if [ -n "{}" ]; then echo Failed\!; echo {} is not writable\!; exit 1; fi"; then
exit 1
fi
echo "Succeeded"
rm -rf $BASE
Now I'm wondering if there might be a better solution (more readable, shorter, reliable, etc).
Please note that I am fully aware of the fact that there could be changes in file access permissions between the check and the actual removal. In my use case, that is acceptable (compared to not doing any checks). If there was a way to avoid this though, I'd love to know how.