Check whether a certain file type/extension exists in directory

前端 未结 15 1560
时光取名叫无心
时光取名叫无心 2021-01-30 06:12

How would you go about telling whether files of a specific extension are present in a directory, with bash?

Something like

if [ -e *.flac ]; then 
echo t         


        
相关标签:
15条回答
  • 2021-01-30 06:36

    For completion, with zsh:

    if [[ -n *.flac(#qN) ]]; then
      echo true
    fi
    

    This is listed at the end of the Conditional Expressions section in the zsh manual. Since [[ disables filename globbing, we need to force filename generation using (#q) at the end of the globbing string, then the N flag (NULL_GLOB option) to force the generated string to be empty in case there’s no match.

    0 讨论(0)
  • 2021-01-30 06:36

    Here's a fairly simple solution:

    if [ "$(ls -A | grep -i \\.flac\$)" ]; then echo true; fi

    As you can see, this is only one line of code, but it works well enough. It should work with both bash, and a posix-compliant shell like dash. It's also case-insensitive, and doesn't care what type of files (regular, symlink, directory, etc.) are present, which could be useful if you have some symlinks, or something.

    0 讨论(0)
  • 2021-01-30 06:38
    #!/bin/bash
    
    count=`ls -1 *.flac 2>/dev/null | wc -l`
    if [ $count != 0 ]
    then 
    echo true
    fi 
    
    0 讨论(0)
  • 2021-01-30 06:41
    #/bin/bash
    
    myarray=(`find ./ -maxdepth 1 -name "*.py"`)
    if [ ${#myarray[@]} -gt 0 ]; then 
        echo true 
    else 
        echo false
    fi
    
    0 讨论(0)
  • 2021-01-30 06:43

    This should work in any borne-like shell out there:

    if [ "$(find . -maxdepth 1 -type f | grep -i '.*\.flac$')" ]; then
        echo true
    fi
    

    This also works with the GNU find, but IDK if this is compatible with other implementations of find:

    if [ "$(find . -maxdepth 1 -type f -iname \*.flac)" ]; then
        echo true
    fi
    
    0 讨论(0)
  • 2021-01-30 06:44

    I tried this:

    if [ -f *.html ]; then
        echo "html files exist"
    else
        echo "html files dont exist"
    fi
    

    I used this piece of code without any problem for other files, but for html files I received an error:

    [: too many arguments
    

    I then tried @JeremyWeir's count solution, which worked for me.

    Keep in mind you'll have to reset the count if you're doing this in a loop:

    count=$((0))
    
    0 讨论(0)
提交回复
热议问题