我发现这个答案很好,但我想了解为什么下面的代码不会检测到两个文件的存在?
if [[ $(test -e ./file1 && test -e ./file2) ]]; then
echo "yep"
else
echo "nope"
fi
直接从 shell 运行它可以按预期工作:
test -e ./file1 && test -e ./file2 && echo yes
的输出test -e ./file1 && test -e ./file2是一个空字符串,这会导致[[ ]]产生一个非零退出代码。你要
if [[ -e ./file1 && -e ./file2 ]]; then
echo "yep"
else
echo "nope"
fi
[[ ... ]]是[ ... ]or的替代品test ...,而不是围绕它的包装器。
if执行程序(或内置程序,在 的情况下[[)并根据其返回值进行分支。您需要省略 the[[ ]]或tests:
if [[ -e ./file1 && -e ./file2 ]]; then
或者
if test -e ./file1 && test -e ./file2; then