Easiest way to check for file extension in bash? [duplicate] Easiest way to check for file extension in bash? [duplicate] bash bash

Easiest way to check for file extension in bash? [duplicate]


You can do this with a simple regex, using the =~ operator inside a [[...]] test:

if [[ $file =~ \.gz$ ]];

This won't give you the right answer if the extension is .tgz, if you care about that. But it's easy to fix:

if [[ $file =~ \.t?gz$ ]];

The absence of quotes around the regex is necessary and important. You could quote $file but there is no point.

It would probably be better to use the file utility:

$ file --mime-type something.gzsomething.gz: application/x-gzip

Something like:

if file --mime-type "$file" | grep -q gzip$; then  echo "$file is gzipped"else  echo "$file is not gzipped"fi


Really, the clearest and often easiest way to match patterns like this in a shell script is with case

case "$f" in*.gz | *.tgz )         # it's gzipped        ;;*)        # it's not        ;;esac


You can try something like this:-

if [[ ${file: -3} == ".gz" ]]