How can I check if a given directory is accessible

2019-01-28 16:52发布

问题:

I am currently writing a script that will list all specific files in a directory. What I need the script to do is to verify that the directory is accessible. I am currently using this bit of code:

# variable used to get the file permissions of the given  directory 
perm=$(stat -c %a "$dir_name")

if [ "$perm" != "755" -o "$perm" != "777" ]; then
  echo ERROR: "Directory $dir_name cannot be accessed check permissions"
  echo USAGE: "ass2 <directory>"
  exit 3
fi

This will work for checking if they have those specific octal permissions, but I was wondering if there is any other way to check if the directory is accessible or not, and to return an error if it isn't.

回答1:

Use Bash Conditional Expressions

On Unix and Linux, practically everything is a file...including directories! If you don't care about execute or write permissions, you can simply check whether a directory is readable with the -r test. For example:

# Check if a directory is readable.
mkdir -m 000 /tmp/foo
[[ -r /tmp/foo ]]; echo $?
1

You can also check whether a file is a traversable directory in a similar way. For example:

# Check if variable is a directory with read and execute bits set.
dir_name=/tmp/bar
mkdir -m 555 "$dir_name"
if [[ -d "$dir_name" ]] && [[ -r "$dir_name" ]] && [[ -x "$dir_name" ]]; then
    : # do something with the directory
fi

You can make the conditionals as simple or as complex as you like, but you don't have to compare octals or parse stat just to check permissions. Bash conditionals can do the job directly.