【问题标题】:Check if a directory exists and is accessible检查目录是否存在且可访问
【发布时间】:2014-05-02 01:27:33
【问题描述】:

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

你能帮我改正吗?

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

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

【问题讨论】:

标签: linux bash unix ksh


【解决方案1】:
if [ -d $dir_test -a -x $dir_test ]

如果你有 /usr/bin/cd:

if [ /usr/bin/cd $dir_test ]

【讨论】:

  • POSIX 标准建议使用[ -d $dir_test ] && [ -x $dir_test ] 代替-a 运算符。
【解决方案2】:
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 可以告诉您目录是否可访问。做吧

cd "$dir_test" || exit 1;

即使您决定首先使用test,出于某种原因,您也应该仍然检查cd 的退出状态,以免出现竞争条件。

【讨论】:

    【解决方案3】:

    编写基于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
    }
    

    【讨论】:

    • 我唯一不明白的部分是如果我使用语句 cd "$dir_test || {exit1}" 它会评估目录是否存在且可访问?
    • 如果cd 成功,则不会评估|| 之后的任何内容。
    • 替代:(cd "$dir_test" || exit; ...)。如果您更改任何变量并且它们需要保留,请使用@chepner 的示例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-05
    • 2013-05-30
    • 2011-02-28
    • 2011-04-25
    • 2013-05-19
    • 2012-09-12
    相关资源
    最近更新 更多