首页 > 解决方案 > 一个 if 条件中的 AND-OR 条件

问题描述

我有 3 个文件

File1=abc.txt File2=def.txt File3=xyz.txt

if [ -f $File1 ] && [ -f $File2 ] && [ -f $File3 ]
then 
   #run some command

否则,如果 3 个文件中的任何一个不存在,它应该告诉我们它是哪个文件。如果它是 2 个不存在的文件,那么它应该告诉这两个文件的名称。

任何人都知道如何做到这一点?

标签: bashshell

解决方案


您可以轻松地将缺少的那些收集到一个数组中,然后从那里取出。

missing=()
for file in abc.txt def.txt xyz.txt; do
    test -e "$file" && continue
    missing+=("$file")
done

if (("${#missing[@]}" == 0 )); then
    # run some command
else
    echo "$0: missing: ${missing[@]}" >&2
fi

如果您希望它是单行的,请将其重构为一个函数;有关简单演示,请参阅https://ideone.com/Oq7cUy


推荐阅读