posts about

How to open files from command line?

January 27, 2021.

xdg-utils is a set of tools for interacting with the deskop environments. It is developed by the project. aims for interoperability between free-software desktop environments which are based on X Window System (X11). To name a few, GNOME, KDE, Xfce are all compatible with specs. What does it mean? That means you can use same executables, scripts and configuration to integrate with your desktop.

Opening a file from command line is that simple with xdg-open

$ 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

  1. file extension
  2. 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

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

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.

comments powered by Disqus Send feedback to me @karakays_.

← Using the man pages wisely