Search code examples
bashdirectoryparent

Checking write permissions on parent directory


I have a slight problem.Basically the problem is trivial, but my solution doesn't seem to work.

The script that I've came up with, goes something like that:

  1. You pass the directory as a $1 parameter. For instance: ./script.sh /Desktop/folder1/folder1submap/myfolder
  2. If the structure /folder1/folder1submap/myfolder doesn't exist I must create it. No problems here, but problem arises because I must first check if the location is writable. I'm testing this with [ -w "target" ] command but it doesn't work because -w is always false if folder doesn't exist. And in my case, it doesn't.

    Solution: Yes I could check the parent folder if it's writable but you cannot know if youre going to get for instance: /Desktop/folder1 or something like this /Desktop/folder1/folder2/folder3/folder4/folder5/ so i can't check the parent folder for rights as easily as I want. To be precise, I cannot know which directory is parent directory if I get arbitrary long path from the user.


Solution

  • One option is to use the dirname command:

    if [ ! -d "$1" ] && [ -w "$(dirname $1)" ]; then 
        mkdir "$1"
    fi