mdpoleto
mdpoleto

Reputation: 803

Checking if any of several globs is matched in shell

I've troubles to understand an if syntax of a line in shell:

if [ ! -f *file1.txt* -a ! -f *file2.txt* -a ! -f *file3.txt* ]; then
    sbatch file.sh
fi

The * is used because my files are backed up to #file.txt.1# format.

As far as I know, the ! creates a 'if not', the -f 'if the string is a file' but I haven't found any function for the -a flag.

I want to submit the file.sh only if all these files are NOT present.

Does anyone could help?

Upvotes: 0

Views: 40

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295443

One easy implementation, compatible with any POSIX shell:

exists_any() {
  while [ "$#" -gt 0 ]; do   # as long as we have command-line arguments...
    [ -e "$1" ] && return 0  # if first argument names a file that exists, success
    shift                    # remove first argument from the list
  done
  return 1                   # nothing matched; report failure
}

if ! exists_any *file1.txt* *file2.txt* *file3.txt*; then
  sbatch file.txt
fi

Upvotes: 2

Related Questions