I like to use Linux, currently in the form of Ubuntu 11.10 “Oneiric”. One thing that has been bothering me is the way how default applications are handled. Setting VLC as my video player of choice under System SettingsSystem InfoDefault Applications didn’t change the fact that most if not all video files were opened with Totem Player by default (see the corresponding Launchpad and Gnome bugs). To play videos with VLC by default, I’d have to browse to the containing folder in Nautilus, bring up the file’s Properties dialog, select VLC under Open With and click Set as default. Now this might be tolerable once, but this procedure has to be repeated once per MP4, AVI, and a plethora of other video file formats. That’s way too point-and-clicky for me. After all this is Linux, right?

At first I couldn’t find a command-line way of setting default applications, but then I came across a forum entry mentioning xdg-mime. That’s exactly what I was looking for. A few minutes and some experiments later I had come up with the following command line:

grep "^MimeType=" /usr/share/applications/vlc.desktop | cut -d "=" -f 2 \
  | xargs -d ';' -n 1 | grep -e "^video/" -e "^x-content/video" \
  | xargs -n 1 -I '{}' xdg-mime default vlc.desktop '{}'

Now that’s the proper Linux-way of handling things 🙂

What it does is check which MIME types VLC supports, extract those from the list that are related to video, and then set them to be opened with VLC by default. Here’s a little play-by-play:

grep "^MimeType=" /usr/share/applications/vlc.desktop

The .desktop file that comes with VLC contains a list of supported MIME types. This extracts the corresponding line.

cut -d "=" -f 2

We only need what’s after the equal sign, so let’s cut that part off.

xargs -d ';' -n 1

Now we have a list of MIME types linked by semicolons. Using xargs with the proper parameters, this is transformed to one line per MIME type.

grep -e "^video/" -e "^x-content/video"

VLC can not only play video but also audio files. For now let’s only use it for videos, i.e. files with MIME types that have video before the slash and a couple others whose MIME types start with x-content/video, e.g. DVDs.

xargs -n 1 -I '{}' xdg-mime default vlc.desktop '{}'

Finally we use xargs once more to execute xdg-mime once per item on the MIME type list. The parameter -I and the braces could be removed, but I like the added clarity they provide.

That’s one of the main reasons why I like Linux: use a couple of small tools, string them together, and you save yourself a lot of time and mouse mileage.