how to use if to see whether file has suffix in shell bash script

This question already has an answer here:

  • String contains in Bash 20 answers

  • You can use the matching operator:

    $ if [[ "abc.def" =~ . ]]; then echo "yes"; else echo "no"; fi
    yes
    
    $ if [[ "abcdef" =~ . ]]; then echo "yes"; else echo "no"; fi
    no
    

    This matches if the dot is the first or last (or only) character in the string. If you expect characters on both sides of the dot, you can do the following:

    $ if [[ "ab.cdef" =~ ... ]]; then echo "yes"; else echo "no"; fi
    yes
    
    $ if [[ ".abcdef" =~ ... ]]; then echo "yes"; else echo "no"; fi
    no
    
    $ if [[ "abcdef." =~ ... ]]; then echo "yes"; else echo "no"; fi
    no
    

    You can also use pattern matching:

    $ if [[ "ab.cdef" == *?.?* ]]; then echo "yes"; else echo "no"; fi
    yes
    
    $ if [[ ".abcdef" == *?.?* ]]; then echo "yes"; else echo "no"; fi
    no
    
    $ if [[ "abcdef." == *?.?* ]]; then echo "yes"; else echo "no"; fi
    no
    

    A good reference for both patterns and regexes is at Greg's Wiki


    bash supports glob-style pattern matching:

    if [[ "$file" = *?.?* ]]; then
       ...
    fi
    

    Note that this assumes a prefix as well - this also ensures that it will not match the . and .. directories.

    If you want to check for a specific extension:

    if [[ "$file" = *?.foo ]]; then
       ...
    fi
    

    echo "xxx.yyy" | grep -q '.'
    if [ $? = 0 ] ; then
        # do stuff
    fi
    

    要么

    echo "xxx.yyy" | grep -q '.' && <one statement here>
    #e.g.
    echo "xxx.yyy" | grep -q '.' && echo "got a dot"
    
    链接地址: http://www.djcxy.com/p/36190.html

    上一篇: 如何从命令行获取Linux中的CPU /内核数量?

    下一篇: 如何查看文件是否在shell bash脚本中有后缀