我想检查目录是否存在并且具有访问权限;如果有,则执行任务。这是我编写的代码,可能没有正确的语法。
你能帮我改正吗?
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
我们如何才能更有效地编写此内容?
编写test
基于原始解决方案的最佳方法是
if test -d "$dir_test" && test –x "$dir_test";
then
cd $dir_test
fi
尽管如果测试失败并且您不更改目录怎么办?脚本的其余部分可能无法按预期工作。
您可以通过使用以下[
同义词来缩短此时间test
:
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
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句