1

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 
2
  • You really ought to quote your variables: file_exists() { [ -f "$1" ]; }. (Although IMO this is a lot cleaner if you write it file_exists() { test -f "$1"; }. The square brackets just seem to cause confusion and offer no benefit over test. Commented May 4, 2022 at 14:54
  • You are confusing exit status with standard output. Commented May 4, 2022 at 16:17

3 Answers 3

4

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1
simple
[ -f /opt/file1 -a -f /opt/file2 ] && { echo "All files exist"; } || { echo "Some files missing"; }
with function
#!/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"
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.