Open files from command line
January 27, 2021.
xdg-utils is a set of tools to interact with the deskop environments. It is developed by the freedesktop.org project that aims for interoperability across different X11-based desktop environments. It doesn’t matter if there is a fully desktop environment say GNOME or only a window manager like i3, one can interact with X11 system in a standard way.
Opening a file from command line is that simple with
$ xdg-open mybook.pdf
xdg-open expects just a path in local file system. Before trigger the application for that file, the file type must be known. How does xdg-open determine the file type?
xdg-utils has another tool to determine file types called
xdg-mime. It checks 2 things in the file in order
- file extension
- if no extension, inspect the file content
xdg-mime relies on file extension. It is certainly possible that the extension might not be properly set. In such cases, an irrelevant application will be triggered to open the unrecognized file but then application will mostly fail. There is a more reliable tool called
file which does more comprehensive checks to determine file types.
$ xdg-mime query filetype mybook.pdf application/pdf
Now that we can determine file’s mime type, it’s time to select the application that opens the file. mimeapps.list is the file where default applications are associated with MIME types. Default applications can be defined at system-level or user-level depending on file’s location. More details on this are in freedesktop specification..
Let’s see what is default application for pdf files
$ xdg-mime query default application/pdf application/pdf=org.gnome.Evince.desktop
pdf files are associated with GNOME’s Evince pdf reader.
Each desktop application is represented with a *.desktop file that reside in /usr/share/applications. It contains meta-data about the application like name, type, icon, mime types it can handle, executable path and so on.
To change default app for pdf files to something else, say firefox browser
$ xdg-mime default firefox-esr.desktop application/pdf
In a nutshell, I use
xdg-open tool to open files in default application. Applications are associated with mime types and this information is stored in mimeapps.list.