elcortegano
elcortegano

Reputation: 2684

Globbing to check whether files with different file extension exist

I'm writing a conditional expression to check whether files a set of required extensions do exist or not. This looks like the following:

if [ ! -f "${FILE}.ext1" ] || [ ! -f "${FILE}.ext2" ] || [ ! -f "${FILE}.ext3" ]; then
        echo "Error: missing extensions"
        exit
fi

I was trying to do so by using a more simpler globbing pattern such as:

if [ ! -f "${FILE}.{ext1,ext2,ext3}" ]; then ...

But this does not work (it does if I use it with a different command like ls -l). Where is the error? Is there an alternative way to simplify the above conditional expression?

Upvotes: 0

Views: 119

Answers (1)

Murphy
Murphy

Reputation: 3999

Two problems here:

  1. The wildcard and brace expansion expressions may not be enclosed by quotes.
  2. The test -f command can't handle multiple arguments.

A working solution is this:

for F in "${FILE}."{ext1,ext2,ext3}; do
    if [ ! -f "${F}" ]; then
        echo "not found: ${F}"
    fi
done

Also make sure you're using #!/bin/bash as shebang at top of the script, as the brace expansion is a bashism, and the script won't be portable to other shells.

Upvotes: 1

Related Questions