我发现这个答案工作正常,但我想了解为什么以下代码不会检测到两个文件的存在?
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)
输出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 ...不是它的包装.
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)