如何检查给定目录是否可访问? [英] How can I check if a given directory is accessible?

查看:98
本文介绍了如何检查给定目录是否可访问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

使用Bash条件表达式

在Unix和Linux上,几乎所有东西都是文件...包括目录!如果您不关心执行或写入权限,则可以使用-r测试简单地检查目录是否可读.例如:

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

您可以根据需要将条件设置得简单或复杂,但不必比较八进制或解析 stat 即可检查权限. Bash条件句可以直接完成这项工作.

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.

这篇关于如何检查给定目录是否可访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆