检查目录是否存在且可访问

Rah*_*ant 5 unix linux bash ksh

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

你能帮我纠正一下吗?

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

我相信这也可以这样写.

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
Run Code Online (Sandbox Code Playgroud)

我们怎样才能更有效地写这个?

che*_*ner 13

编写原始test解决方案的最佳方法是

if test -d "$dir_test" && test –x "$dir_test";
then
    cd $dir_test
fi
Run Code Online (Sandbox Code Playgroud)

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

您可以使用以下[同义词来缩短此时间test:

if [ -d "$dir_test" ] && [ -x "$dir_test" ]; then
Run Code Online (Sandbox Code Playgroud)

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

if [[ -d "$dir_test" && -x "$dir_test" ]]; then
Run Code Online (Sandbox Code Playgroud)

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

cd "$dir_test" || {
  # Take the appropriate action; one option is to just exit with
  # an error.
  exit 1
}
Run Code Online (Sandbox Code Playgroud)