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

This question already has an answer here:


ANSWERS:


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

Or

echo "xxx.yyy" | grep -q '\.' && <one statement here>
#e.g.
echo "xxx.yyy" | grep -q '\.' && echo "got a dot"

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


 MORE:


 ? how to use if to see whether file has suffix in shell bash script
 ? how to use if to see whether file has suffix in shell bash script
 ? String contains in Bash
 ? String contains in Bash
 ? String contains in Bash
 ? String contains in Bash
 ? How do you tell if a string contains another string in Unix shell scripting?
 ? How do you tell if a string contains another string in Unix shell scripting?
 ? How do you tell if a string contains another string in Unix shell scripting?
 ? Shell scripting: test if a string contains a character (including chars like '*' and '\')