Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a shell script where I need to do one command if a file is zipped (ends in .gz) and another if it is not. I'm not really sure how to approach this, here's an outline of what I'm looking for:

file=/path/name*  if [ CHECK FOR .gz ] then echo "this file is zipped" else echo "this file is not zipped" fi 
like image 880
Liam Avatar asked Aug 16 '13 17:08

Liam


People also ask

How do I see file extensions in Bash?

Using Bash, there's also ${file%. *} to get the filename without the extension and ${file##*.} to get the extension alone. That is, file="thisfile.

How do I check the extension of a file in Linux?

To find out file types we can use the file command. Using the -s option we can read the block or character special file. Using -F option will use string as separator instead of “:”. We can use the –extension option to print a slash-separated list of valid extensions for the file type found.

How do I remove a filename extension in Bash?

Remove File Extension Using the basename Command in Bash If you know the name of the extension, then you can use the basename command to remove the extension from the filename. The first command-Line argument of the basename command is the variable's name, and the extension name is the second argument.


2 Answers

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.gz something.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 
like image 159
rici Avatar answered Oct 12 '22 04:10

rici


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 
like image 41
jthill Avatar answered Oct 12 '22 06:10

jthill