Given a mime-type get the corresponding file extension

curlfilenamesmime-types

I want to download a file using curl to a temporary directory with the appropriate extension.

Currently I do something like this:

tmp="$(mktemp -t 'curl')"
curl -o "$tmp" http://example.com/generate_image.php?id=44
file -b --mime-type "$tmp"

This will print the mime-type of the downloaded file, but how do I map these to extensions?

As you can see I can't just extract the "extension" of the url as that would give .php instead of .png.

I know there isn't a one-to-one map between mime-types and file extensions but it should handle normal file extensions.

Best Answer

Unlike windows, unix generally has no concept of file extensions. However you can use the /etc/mime.types file to provide those translations:

image/jpeg: jpg
image/gif: gif
image/png: png
image/x-portable-pixmap: ppm
image/tiff: tif

and then match by extension:

$ ext=$(grep "$(file -b --mime-type file.png)" /etc/mime.types | awk '{print $2}')

$ echo $ext
png
Related Question