bash 检查目录是否存在并且可以访问
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22613656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if a directory exists and is accessible
提问by Rahul sawant
I want to check if a directory exists and it has access rights; if it does, then perform the tasks. This is the code I wrote, which might not have proper syntax.
我想检查一个目录是否存在并且它有访问权限;如果是,则执行任务。这是我写的代码,它可能没有正确的语法。
Can you help me to correct it?
你能帮我改正吗?
dir_test=/data/abc/xyz
if (test -d $dir_test & test –x $dir_test -eq 0);
then
cd $dir_test
fi
I believe this can also be written like this.
我相信这也可以这样写。
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
How can we write this more efficiently?
我们怎样才能更有效地写这个?
回答by chepner
The best way to write the original test
-based solution would be
编写test
基于原始解决方案的最佳方法是
if test -d "$dir_test" && test –x "$dir_test";
then
cd $dir_test
fi
although what will you do if the test fails and you don'tchange directories? The remainder of the script will probably not work as expected.
如果测试失败并且您不更改目录,您会怎么做?脚本的其余部分可能不会按预期工作。
You can shorten this by using the [
synonym for test
:
您可以使用以下[
同义词来缩短它test
:
if [ -d "$dir_test" ] && [ -x "$dir_test" ]; then
or you can use the conditional command provided by bash
:
或者您可以使用以下提供的条件命令bash
:
if [[ -d "$dir_test" && -x "$dir_test" ]]; then
The best solution, since you are going to change directories if the tests succeed, is to simply tryit, and abort if it fails:
最好的解决方案,因为如果测试成功,您将更改目录,只需尝试一下,如果失败则中止:
cd "$dir_test" || {
# Take the appropriate action; one option is to just exit with
# an error.
exit 1
}
回答by kojiro
dir_test=/data/abc/xyz
if (test -d $dir_test & test –x $dir_test -eq 0); # This is wrong. The `-eq 0` part will result in `test: too many arguments`. The subshell (parens) is also unnecessary and expensive.
then
cd $dir_test
fi
cd
can tell you if a directory is accessible. Just do
cd
可以告诉您目录是否可访问。做就是了
cd "$dir_test" || exit 1;
Even if you do decide to use test
first, for some reason, you should stillcheck the exit status of cd
, lest you have a race condition.
即使您决定首先使用test
,出于某种原因,您仍然应该检查 的退出状态cd
,以免出现竞争条件。
回答by Joshua
if [ -d $dir_test -a -x $dir_test ]
alternatively if you have /usr/bin/cd:
或者,如果您有 /usr/bin/cd:
if [ /usr/bin/cd $dir_test ]