4

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.

Oliver Salzburg
  • 21,652
  • 20
  • 93
  • 138

1 Answers1

6

Are you aware of the -perm switch of find (if it is present in your version)?

find -perm -u+w
choroba
  • 231,213
  • 25
  • 204
  • 289
  • No, I wasn't. Thanks for the hint. I'll take that into consideration. – Oliver Salzburg Jan 02 '12 at 16:45
  • Ok, I give up. How can I properly inverse the test? Your example lists all files I have write access to. How do I list all files I don't have write access to? I can't get it to work. `find . ! -perm -u+w` lists nothing, while my original approach lists tons of files. – Oliver Salzburg Jan 02 '12 at 17:11
  • @fge That doesn't list anything either (testing on Debian 6). `find . ! -writable` works great, but according to http://stackoverflow.com/a/4382672/259953 it might be less portable. – Oliver Salzburg Jan 02 '12 at 17:31
  • I marked your solution as the correct one even though I never got it to work. But I hope that's a problem with my specific version of find and/or environment. – Oliver Salzburg Feb 28 '12 at 12:05
  • @OliverSalzburg: What about `find -not -perm -u+w` instead of `!` that can get interpreted by the history expansion of your shell? – choroba Feb 29 '12 at 15:55
  • @choroba No, that makes no difference. The `!` doesn't cause any trouble when using `-writable`. I don't understand why it doesn't work. – Oliver Salzburg Feb 29 '12 at 16:17
  • @OliverSalzburg: Access Control Lists maybe? – choroba Mar 01 '12 at 11:52
  • 2
    @OliverSalzburg: Heh. The `-perm -u+w` checks whether the file is writable by its owner, not by the user running `find`. – choroba Mar 01 '12 at 17:41
  • @choroba That explains a lot. – Oliver Salzburg Mar 01 '12 at 19:59