Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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?

share|improve this question
add comment

1 Answer 1

up vote 9 down vote accepted

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.

share|improve this answer
    
Exactly what I was looking for! Do you know if xdg-open can tell the command used to open, for example, PNG files ? –  Gradient Jan 31 '13 at 3:08
    
I've updated my answer. –  Dennis Jan 31 '13 at 3:24
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.