Search code examples
bashfilesearch

check if file exists that has digits in it


I have following code:

config_path="mypath/"
outD="outDir/"

for doms in Germ500 Port500 Spai500;do
    echo "animating for: ${doms}"
    config_name="${doms}_config.toml"
    # Check if the Germ500_titt_20240903T0000_animation.html exists, otherwise make new
    # 
    [ ! -f "${outD}${doms}_titt_[????????]T[????]_animation.html" ] && echo "File does not exist: make new" || echo "${outD}${doms}_titt_[????????]T[????]_animation.html exist"

done

How can I fix the command?

I tried the following:

[ ! -f "${outD}${doms}_titt_[0-9]{8}T[0-9]{4}_animation.html" ] && echo "File does not exist: make new" || echo "${outD}${doms}_titt_[????????]T[????]_animation.html exist"


Solution

  • The wildcard [????????]T[????] is equivalent to [?]T[?] (character classes only match a single character), which will only match the literal filename ?T?. If you want to match digits, you must use [0-9], i.e. [0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]T[0-9][0-9][0-9][0-9].

    But test -f ([ -f … ]) can only handle a single path. Quoting an expression will prevent glob expansion, but even if the glob were expanded, your script would break because, again, -f only handles a single path.

    Can I interest you in a find-based solution instead?

    if test "$(find "$outD" -maxdepth 1 -name "${doms}_titt_[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]T[0-9][0-9][0-9][0-9]_animation.html" -print -quit)"; then
      echo 'file matching pattern exists'
    else
      echo 'no file matching pattern found'
    fi
    

    or a loop-based one?

    for file in "$outD/${doms}_titt_"[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]T[0-9][0-9][0-9][0-9]_animation.html; do
      if test -f "$file"; then
        echo "file $file exists"
      else
        echo "no file matching pattern found"
      fi
      break
    done
    

    It's not bullet proof and could lead to unexpected results if you have a file with the literal pattern as name.

    Find additional (portable or bash-only) solutions in Test whether a glob has any matches in Bash