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 which aims for interoperability across X11-based desktop environments. In other words, it doesn’t matter if I have a fully desktop environment say GNOME or only a window manager like i3, I can interact with X11 system in a standard way.
Opening a file from command line is as simple as
$ xdg-open mybook.pdf
xdg-open expects just a path in local file system. Now it executes the application that is related to this file. It needs to know file type first. Is it text, image, binary or something else?
xdg-utils has another tool to determine file types,
xdg-mime. To understand file’s content, it checks 2 things in order
- file extension
- if there is no extension or is unknown, inspect the file content
xdg-mime relies on file extension. However, the extension might not be properly set in which case an irrelevant application will try to open the file and it will 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 file’s mime type is known, 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
xdg-mime outputs, 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