BASH :从 IF 语句调用函数并比较 return 值。为多个功能执行此操作

BASH : Calling functions from IF statement and comparing the return value. Doing this for multiple functions

我有一个函数可以检查路径中是否存在文件

file_exists () 
{
 [ -f  ]
}

我的要求是检查不同路径中的多个文件(在本例中为 2 个文件)。 如果两个文件都存在,那么我应该继续下一步。

这里我想到了用一个 AND 门的 IF 条件,但是无法得到我期望的结果。

永远不会从 IF 条件调用该函数。

谁能帮我解决我的需求,我怎样才能写得更好?

if [[ $(file_exists /opt/file1) == "0" && $(file_exists /temp/file2) == "0" ]]; 
then
 #next steps code here 
else 
 echo " some files missing" 
fi 

当您使用 $(command) 时,它被替换为命令的标准输出,而不是其退出状态。由于您的函数不产生任何输出,因此它永远不会等于 "0".

您不需要 [[ 来测试退出状态,if 命令会自动完成。

if file_exists /opt/file1 && file_exists /tmp/file2
then
    # next steps here
else
    echo "Some files missing"
fi

如果您想节省重写相同的调用。您可以使用一个函数来测试所有文件是否存在:

all_files_exist () 
{
  while [ $# -gt 0 ]
  do
    [ -f "" ] || return 1
    shift
  done
}

if all_files_exist /opt/file1 /temp/file2
then
  printf 'All files exist.\n'
else
  printf 'Some files are missing.\n' >&2
  exit 1
fi
简单
[ -f /opt/file1 -a -f /opt/file2 ] && { echo "All files exist"; } || { echo "Some files missing"; }
有功能
#!/bin/bash

allExist(){
 for file in $@
 do
   [ ! -f $file ] && return 1
 done
 return 0
}

FILES="/opt/file1 /opt/file2"

allExist $FILES  && {
  echo "All files exist"
  } || {
  echo "Some files missing"
}