pwned

I wrote the below BASH function today. It’s good because it performs super well compared to the alternative commands (which are commented out below above the new commands):

own() {

  echo "Taking ownership..."
  #chown -R jj5:jj5 .
  find . \! -user jj5 -or \! -group jj5 -execdir chown jj5:jj5  "{}" \;
  [ "$?" = 0 ] || { echo "Could not take ownership in '$PWD'."; exit 1; }

  echo "Fixing directory permissions..."
  #find . -type d -execdir chmod u+rwx "{}" \;
  find . -type d -and \( \! -perm /u=r -or \! -perm /u=w -or \! -perm /u=x \) -execdir chmod u+rwx "{}" \;
  [ "$?" = 0 ] || { echo "Could not fix directory permissions in '$PWD'."; exit 1; }

  echo "Fixing file permissions..."
  #find . -type f -execdir chmod u+rw "{}" \;
  find . -type f -and \( \! -perm /u=r -or \! -perm /u=w \) -execdir chmod u+rw "{}" \;
  [ "$?" = 0 ] || { echo "Could not fix file permissions in '$PWD'."; exit 1; }

}

The basic premise is don’t do work which doesn’t need to be done!

Making directories executable and files read and writeable

I had a problem with my rsync backups. The problem was that the first time I ran it everything worked fine. The second time it ran (and all subsequent times) I got back the phone book of error messages, because the first time I’d run rsync it had copied in a whole heap of read-only files, and then when I ran it again it wasn’t able to overwrite those read-only files. At least I think that was what was happening. So I added the following to my backup script:

  find . -type d -exec chmod u+x {} \;
  if [ "$?" -ne "0" ]; then
    echo "Cannot chmod directories in '$PWD'.";
    exit 1;
  fi
  find . -type f -exec chmod u+rw {} \;
  if [ "$?" -ne "0" ]; then
    echo "Cannot chmod files in '$PWD'.";
    exit 1;
  fi

This code runs after rsync and processes the files and directories that have been synchronised. That is, it processes the copy of the data, not the data I copied from.

For the copy of the data I want to make sure that the owner of the files can read and write them and that the owner of the directories can execute them. So that’s what the above code does.