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

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

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

你能帮我纠正一下吗?

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

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

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

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

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

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

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
}
原文链接:https://www.f2er.com/linux/440383.html

猜你在找的Linux相关文章