How does Linux know what is the mimetype of a file?

3

How can linux know the mimetype of a file? Is there something written inside the file? Does it look at the extension of the file?

Gradient

Posted 2013-05-16T13:04:20.813

Reputation: 531

Answers

5

Through the "magic" bytes in a file. You can do this yourself by running the file command:

file --mime filename

To my understanding, the underlying library is libmagic.

Der Hochstapler

Posted 2013-05-16T13:04:20.813

Reputation: 77 228

3

It does use extensions as well... because things like .txt don't necessarily have good magic bytes to look for. The exact implementation may depend on which Desktop Environment you mean (e.g. KDE v.s. GNOME). However this is an old freedesktop standard, so the behaviour of most DEs should be very similar.

– sourcejedi – 2013-05-16T13:38:44.457

How are magic bytes store in a file in practice? In a text file for example? – Gradient – 2013-05-16T15:04:48.903

@Gradient: There are multiple places. Like /usr/share/mime/magic, and /usr/share/file/magic.mgc (binary). You can also add your own signatures in /etc/magic. At least these are valid files on my Debian system. – Der Hochstapler – 2013-05-16T15:08:15.593

2Plain text files are mainly recognized from the absence of certain bytes that stand for unprintable characters. – chirlu – 2013-05-16T17:31:29.807