Bash,测试是否存在两个文件

时间:2013-05-21 16:16:54

标签: bash

我发现this answer which works很好,但我想了解为什么以下代码无法检测到两个文件的存在?

if [[ $(test -e ./file1 && test -e ./file2) ]]; then
  echo "yep"
else
  echo "nope"
fi

直接从shell运行它可以按预期工作:

test -e ./file1 && test -e ./file2 && echo yes

2 个答案:

答案 0 :(得分:7)

test -e ./file1 && test -e ./file2的输出是一个空字符串,这会导致[[ ]]生成非零退出代码。你想要

if [[ -e ./file1 && -e ./file2 ]]; then
    echo "yep"
else
    echo "nope"
fi

[[ ... ]]替代[ ... ]test ...,而不是它的包装。

答案 1 :(得分:5)

if执行一个程序(或在[[的情况下内置)并根据其返回值进行分支。您需要省略[[ ]]test s:

if [[ -e ./file1 && -e ./file2 ]]; then

if test -e ./file1 && test -e ./file2; then