加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

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

发布时间:2020-05-24 17:10:22 所属栏目:Linux 来源:互联网
导读:我想检查一个目录是否存在,它是否具有访问权限;如果是,则执行任务.这是我写的代码,可能没有正确的语法.你能帮我纠正一下吗?dir_test=/data/abc/xyz if (test -d $dir_test test –x $dir_test -eq 0); then cd $dir_test fi 我相信这也可以这样写.dir_test=

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

你能帮我纠正一下吗?

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
}

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读