Search code examples
bashvariable-expansion

How can I check if exists file with name according to "template" in the directory?


Given variable with name template , for example: template=*.txt.
How can I check if files with name like this template exist in the current directory?

For example, according to the value of the template above, I want to know if there is files with the suffix .txt in the current directory.


Solution

  • Use find:

    : > found.txt  # Ensure the file is empty
    find . -prune -exec find -name "$template" \; > found.txt
    if [ -s found.txt ]; then
      echo "No matching files"
    else
      echo "Matching files found"
    fi
    

    Strictly speaking, you can't assume that found.txt contains exactly one file name per line; a filename with an embedded newline will look the same as two separate files. But this does guarantee that an empty file means no matching files.

    If you want an accurate list of matching file names, you need to disable field splitting while keeping pathname expansion.

    [[ -v IFS ]] && OLD_IFS=$IFS
    IFS=
    shopt -s nullglob
    files=( $template )
    [[ -v OLD_IFS ]] && IFS=$OLD_IFS
    printf "Found: %s\n" "${files[@]}"
    

    This requires several bash extensions (the nullglob option, arrays, and the -v operator for convenience of restoring IFS). Each element of the array is exactly one match.