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

前端之家收集整理的这篇文章主要介绍了linux – 检查目录是否存在且可访问前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

你能帮我纠正一下吗?

  1. dir_test=/data/abc/xyz
  2. if (test -d $dir_test & test x $dir_test -eq 0);
  3. then
  4. cd $dir_test
  5. fi

我相信这也可以这样写.

  1. dir_test=/data/abc/xyz
  2. test -d $dir_test
  3. if [ $? -eq 0 ];
  4. then
  5. test x $dir_test
  6. if [ $? -eq 0 ];
  7. then
  8. cd $dir_test
  9. fi
  10. fi

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

最佳答案
编写原始基于测试的解决方案的最佳方法

  1. if test -d "$dir_test" && test x "$dir_test";
  2. then
  3. cd $dir_test
  4. fi

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

您可以使用[测试的同义词来缩短此时间:

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

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

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

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

  1. cd "$dir_test" || {
  2. # Take the appropriate action; one option is to just exit with
  3. # an error.
  4. exit 1
  5. }

猜你在找的Linux相关文章