Search code examples
bashshellwildcard

If file with different extension is missing


This seems simple but I haven't been able to modify my script to make it work (attempts are commented out). This is a script that searches for raw files, and if there's no associated jpg file, it does something (to produce a corresponding jpg, but that's not the issue here). The script below works fine for that.

The problem is that file.raw can have an associated file.jpg, but also sometimes file.something.jpg, which... I haven't been able to add to shoehorn in the script.

#! /bin/bash

shopt -s nullglob       # Avoid *.something result in for loop

for File in *.{rw2,raf,raw,dng,nef,cr2,new,orf}
do
#       if compgen -G "${File%.*}"*jpg > /dev/null
#       find . -maxdepth 1 -name "${File%.*}*jpg"
#       if test -n "$(find . -maxdepth 1 -name '${File%.*}*jpg' -print -quit)"

        if [ ! -f "${File%.*}.jpg" ];
        then
                # Do something
        fi
done

So in summary:

  • if file.raw and no file*.jpg -> do something
  • if file.raw and any file*.jpg -> do nothing I think the nullglob necessary for the for loop breaks things up for the other wildcards...

Solution

  • You can't use -f on a wildcard if it could match more than one file; and you can't put the wildcard inside quotes, because that protects it from the shell.

    #! /bin/bash
    
    shopt -s nullglob       # Avoid *.something result in for loop
    
    for File in *.{rw2,raf,raw,dng,nef,cr2,new,orf}
    do
        files=("${File%.*}"*".jpg")
        if [[ ! -f "${files[0]}" ]]
        then
            # Do something
        fi
    done