Home > OS >  Checking for multiple files with bash script
Checking for multiple files with bash script

Time:10-18

I have a bash file where I am currently using an if statement to check for two files existing before continuing with the rest.

if [[ -e $flchck ]] && [[ -e $flchck2 ]]; then

--do stuff here

else

--sends me an email telling me the files were not found.

My question is, is this the most efficient way to do this? If I need it to check more files, would I just keep adding && to include more.

What if I want it to tell me which file(s) was missing when it did this check.

Any guidance/direction on how to handle this would be greatly appreciated.

CodePudding user response:

Typically one would use an array for this purpose. Assuming that your error-report-mailing code is encapsulated in a command named send_error_email, this may look like:

#!/usr/bin/env bash
files=( /path/to/file1 /path/to/file2 /path/to/file3 )
for file in "${files[@]}"; do
  if ! [[ -e $file ]]; then
    send_error_email "$file does not exist"
    exit 1
  fi
done
# do stuff here
  •  Tags:  
  • bash
  • Related