linux – 检查目录是否存在且可访问
发布时间:2020-12-14 02:09:52 所属栏目:Linux 来源:网络整理
导读:我想检查一个目录是否存在,它是否具有访问权限;如果是,则执行任务.这是我写的代码,可能没有正确的语法. 你能帮我纠正一下吗? dir_test=/data/abc/xyzif (test -d $dir_test test –x $dir_test -eq 0); thencd $dir_testfi 我相信这也可以这样写. 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 } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |