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

AJP*_*AJP 1 bash

我发现这个答案工作正常,但我想了解为什么以下代码不会检测到两个文件的存在?

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

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

test -e ./file1 && test -e ./file2 && echo yes
Run Code Online (Sandbox Code Playgroud)

che*_*ner 7

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

if [[ -e ./file1 && -e ./file2 ]]; then
    echo "yep"
else
    echo "nope"
fi
Run Code Online (Sandbox Code Playgroud)

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


Kev*_*vin 5

if执行程序(或在内核中[[),并根据其返回值执行分支.您需要忽略要么[[ ]]testS:

if [[ -e ./file1 && -e ./file2 ]]; then
Run Code Online (Sandbox Code Playgroud)

要么

if test -e ./file1 && test -e ./file2; then
Run Code Online (Sandbox Code Playgroud)