Register file extensions / mime types in Linux

Viewed 33323

I'm developing a Linux application that has its own file format. I want my app to open when you double-click on those files.

How can I register a file extension and associate it with my application on Linux? I'm looking for a way that is standard (works with GNOME and KDE based systems) and can be done automatic when my program is installed or run for the first time.

5 Answers

Use xdg-utils from freedesktop.org Portland.

Register the icon for the MIME type:

xdg-icon-resource install --context mimetypes --size 48 myicon-file-type.png x-application-mytype

Create a configuration file (freedesktop Shared MIME documentation):

<?xml version="1.0"?>
<mime-info xmlns='http://www.freedesktop.org/standards/shared-mime-info'>
  <mime-type type="application/x-mytype">
    <comment>A witty comment</comment>
    <comment xml:lang="it">Uno Commento</comment>
    <glob pattern="*.myapp"/>
  </mime-type>
</mime-info>

Install the configuration file:

xdg-mime install mytype-mime.xml

This gets your files recognized and associated with an icon. xdg-mime default can be used for associating an application with the MIME type after you get a .desktop file installed.

1) in linux this is a function of your desktop environment rather than the os itself.
2) GNOME and KDE have different methods to accomplish this.
3) There's nothing stopping you from doing it both ways.

This is all existing answers combined, completed and corrected into a single bash script.

#!/bin/bash
set -e # stop on error

APP=my-app
EXT=my-app
COMMENT=Comment
EXEC=/usr/bin/my-app
LOGO=./logo.png

xdg-icon-resource install --context mimetypes --size 48 $LOGO application-x-$APP

echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">
    <mime-type type=\"application/x-$APP\">
        <comment>$COMMENT</comment>
        <icon name=\"application-x-$APP\"/>
        <glob pattern=\"*.$EXT\"/>
    </mime-type>
</mime-info>" > $APP-mime.xml

xdg-mime install $APP-mime.xml
rm $APP-mime.xml
update-mime-database $HOME/.local/share/mime

echo "[Desktop Entry]
Name=$APP
Exec=$EXEC %U
MimeType=application/x-$APP
Icon=application-x-$APP
Terminal=false
Type=Application
Categories=
Comment=$COMMENT
"> $APP.desktop
desktop-file-install --dir=$HOME/.local/share/applications $APP.desktop
rm $APP.desktop
update-desktop-database $HOME/.local/share/applications

xdg-mime default $APP.desktop application/x-$APP

Related