Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

bash - How can I check if a given directory is accessible?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...