我目前正在编写一个脚本,该脚本将列出目录中的所有特定文件。我需要脚本执行的操作是验证目录是否可访问。我目前正在使用以下代码:
# 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
这将用于检查它们是否具有那些特定的八进制权限,但是我想知道是否还有其他方法可以检查目录是否可访问,如果无法访问则返回错误。
在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
您可以根据需要将条件设置得简单或复杂,但不必为了检查权限而比较八进制或解析统计信息。Bash条件句可以直接完成这项工作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句