How to open file with default program from command line?

10

2

If I click on a file in a GUI file explorer, a default program is used to open it. This is useful for files which I don't know how to open from the command line.

Is there a way to open a file with the default program using command-line instead?

Alternatively, is there a way, given a file extension, to determine a command to open it?

Gradient

Posted 2013-01-31T01:56:58.087

Reputation: 531

Answers

14

Is there a way to open a file with the default program using command-line instead?

This is a job for xdg-open:

xdg-open opens a file or URL in the user's preferred application. If a URL is provided the URL will be opened in the user's preferred web browser. If a file is provided the file will be opened in the preferred application for files of that type. xdg-open supports file, ftp, http and https URLs.

  • Syntax for opening a file with it's default application:

    xdg-open {file}
    

xdg-open comes pre-installed in Ubuntu.

Alternatively, is there a way, given a file extension, to determine a command to open it?

By the extension, no. The default application is chosen based upon the MIME type, not the extension. Linux does not have "extensions".

For a specific file, you can use xdg-mime to determine both the file's MIME type and the default application associated to it:

  • Syntax for displaying a file's MIME type:

    xdg-mime query filetype {file}
    
  • Syntax for displaying MIME type's default application:

    xdg-mime query default {mimetype}
    
  • Syntax for displaying a file's default application:

    xdg-mime query default "$(xdg-mime query filetype {file})"
    

As a (hacky) workaround you could use the command

xdg-mime query default \
    `xdg-mime query filetype "$(find ~ / -iname '*.png' -print -quit)"`

to display the default application for, e.g., PNG images.

This will work if and only if you have a PNG image on your computer and the first found file ending with .png is a valid PNG image.

Dennis

Posted 2013-01-31T01:56:58.087

Reputation: 42 934

Exactly what I was looking for! Do you know if xdg-open can tell the command used to open, for example, PNG files ? – Gradient – 2013-01-31T03:08:35.310

I've updated my answer. – Dennis – 2013-01-31T03:24:15.570