检查一个目录是否存在并且可以访问

我想检查一个目录是否存在,它有访问权限; 如果是,则执行任务。 这是我写的代码,可能没有正确的语法。

你能帮我纠正吗?

dir_test=/data/abc/xyz if (test -d $dir_test & test –x $dir_test -eq 0); then cd $dir_test fi 

我相信这也可以这样写。

 dir_test=/data/abc/xyz test -d $dir_test if [ $? -eq 0 ]; then test –x $dir_test if [ $? -eq 0 ]; then cd $dir_test fi fi 

我们如何更有效地写这个?

编写原始的基于test的解决方案的最好方法是

 if test -d "$dir_test" && test –x "$dir_test"; then cd $dir_test fi 

虽然如果测试失败,你会怎么做,你改变目录? 脚本的其余部分可能无法按预期工作。

您可以通过使用[ test同义词:

 if [ -d "$dir_test" ] && [ -x "$dir_test" ]; then 

或者你可以使用bash提供的条件命令:

 if [[ -d "$dir_test" && -x "$dir_test" ]]; then 

最好的解决方案,因为如果测试成功,您将要更改目录,只需简单地尝试一下,如果失败则中止:

 cd "$dir_test" || { # Take the appropriate action; one option is to just exit with # an error. exit 1 } 
 dir_test=/data/abc/xyz if (test -d $dir_test & test –x $dir_test -eq 0); # This is wrong. The `-eq 0` part will result in `test: too many arguments`. The subshell (parens) is also unnecessary and expensive. then cd $dir_test fi 

cd可以告诉你,如果一个目录是可访问的。 做就是了

 cd "$dir_test" || exit 1; 

即使你决定首先使用test ,由于某种原因,你仍然应该检查cd的退出状态,以免你有一个竞争条件。

 if [ -d $dir_test -a -x $dir_test ] 

或者如果你有/ usr / bin / cd:

 if [ /usr/bin/cd $dir_test ]