Bash 如何检查给定目录是否可访问?

Bash 如何检查给定目录是否可访问?,bash,directory,file-permissions,exit-code,Bash,Directory,File Permissions,Exit 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

我目前正在编写一个脚本,它将列出目录中的所有特定文件。我需要脚本做的是验证目录是否可访问。我目前正在使用以下代码:

# 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
#用于获取给定目录的文件权限的变量
perm=$(stat-c%a“$dir\u name”)
如果[“$perm”!=“755”-o“$perm”!=“777”];然后
echo错误:“无法访问目录$dir\u name检查权限”
回显用法:“ass2”
出口3
fi
这将用于检查他们是否具有那些特定的八进制权限,但我想知道是否有其他方法来检查目录是否可访问,如果不可访问则返回错误。

使用Bash条件表达式 在Unix和Linux上,几乎所有内容都是一个文件…包括目录!如果您不关心执行或写入权限,只需使用
-r
测试检查目录是否可读即可。例如:

# Check if a directory is readable.
mkdir -m 000 /tmp/foo
[[ -r /tmp/foo ]]; echo $?
1
# 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
您还可以以类似的方式检查文件是否为可遍历目录。例如:

# Check if a directory is readable.
mkdir -m 000 /tmp/foo
[[ -r /tmp/foo ]]; echo $?
1
# 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
您可以根据自己的喜好使条件语句变得简单或复杂,但不必仅为了检查权限而比较八进制或解析stat。Bash条件可以直接完成这项工作