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

Time:05-05

I have a function to check if a file exists in a path or not

file_exists () 
{
 [ -f $1 ]
}

My requirement is to check for multiple files (in this case 2 files) which are in different paths. If both files exist then only I should move to next step.

Here I thought of using IF condition with an AND gate, but unable to get the result I'm expecting.

The function is never getting called from the IF condition.

Can someone help me with my requirement and also how can I write it better?

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

CodePudding user response:

When you use $(command), it's replaced with the standard output of the command, not its exit status. Since your function doesn't produce any output, it will never be equal to "0".

You don't need [[ to test the exit status, the if command does that by itself.

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

CodePudding user response:

If you want to save on rewriting the same call ever. You can use a function to test all files exist:

all_files_exist () 
{
  while [ $# -gt 0 ]
  do
    [ -f "$1" ] || 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
  • Related