'How to check linux directory permission for current user which doesn't exist

I have an application where user enters some path which application uses to create directory if doesn't exist and add logging files. Now I want to check if current linux user has permission to create this directory path or not in case it doesn't exist. To give an example suppose /tmp/test is some directory which exists on machine and user enters /tmp/test/apps/log. How can i check write permission to this directory if it doesn't exist? I need to do it via shell command so that I can automate it. Thanks



Solution 1:[1]

You need to check if any of the ancestor directories are writable, and if anything would be blocking the creation. There are quite a bit of corner cases, so I might have forgotten some.

#!/bin/bash

# Syntax: can_mkdir_p [-f] <path>
#     -f   Succeed if the directory already exists and is writable
function can_mkdir_p() {
  if [ "$1" == -f ]
  then
    exist_result=0
    shift
  else
    exist_result=66
  fi

  dir="$1"
  if [ -f "$dir" ]
  then
    # the requested path is an existing file, so mkdir is blocked.
    return 65
  elif [ -d "$dir" ]
  then
    # the requested path is an existing directory.
    if [ -w "$dir" ]
    then
      # it is writable; if -f is supplied, it is okay
      # otherwise, report that mkdir is blocked
      return "$exist_result"
    else
      # the directory is not writable; report a permission problem
      return 64
    fi
  fi

  # if the path does not exist, check ancestor directories
  while [ "$dir" != / ]
  do
    parent=$(dirname "$dir")
    if [ -w "$parent" ]
    then
      # the parent is writable, so maybe we can mkdir -p
      if [ -f "$dir" ]
      then
        # nope, a file already exists here that would block mkdir -p
        return 65
      elif [ -d "$dir" ]
      then
        # nope, a directory already exists here;
        # if it was writeable, we would have reported okay
        # in the previous iteration
        return 64
      else
        # we found a writable ancestor that is not blocked, report okay
        return 0
      fi
    fi
    # this level is not okay, try one level up
    dir="$parent"
  done
  # reached the root, still not okay
  return 64
}

# example usage
if can_mkdir_p "$@"
then
  echo Okay
else
  case "$?" in
    64)
      echo "No write permission"
      ;;
    65)
      echo "Something is in the way"
      ;;
    66)
      echo "Already exists"
  esac
fi

But as I said in the comments, you can just try to make a directory and if it fails, complain to the user. This is what most software does.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Amadan