How to get the mime type of a file from the command line?

I'm trying to get the mime type of a file from the command line as a printed string (eg. application/vnd.oasis.opendocument.spreadsheet).

I looked up how to do this and found the xdg-mime command.

From reading the man page (man xdg-mime), it seems I should run xdg-mime query filetype FILE. However, when I run this with any file it prints nothing and exits.

Is there a way to fix this? An alternative command?


Solution 1:

Use file --mime-type -b filename

Look at file --help for more tips.

Solution 2:

The great answer on this page can be put in a function or script like so:

Example

$ mime_type.sh /etc/passwd  
text/plain

mime_type.sh

function mime_type()
{
  file --mime-type -b $*
}

mime_type $*

Solution 3:

xdg-mime and file query different databases (xdg-mime is more comprehensive). See Why the difference between the results with "file --mime-type" and "xdg-mime query filetype"? for more discussion.

xdg-mime does not work correctly from a non-desktop session (e.g. if you're SSH'd into a machine).

Solution 4:

mimetype /path/to/file

Tested in 18.04