Ubuntu – Running a .desktop file in the terminal

command linedesktopshortcuts

From what I can gather, .desktop files are shortcuts that allow application's settings to be customized. For instance, I have lots of them in my /usr/share/applications/ folder.

If I open that folder in nautilus, I can run these applications just by double clicking its associated file, e.g. double-clicking firefox.desktop runs Firefox. However, I can't find a way to do the same thing via terminal.

If I do gnome-open foo.desktop it simply opens foo.desktop as a text file. If I make it executable and then run it in bash it simply fails (which is expected, it's clearly not bash script).
EDIT: Doing exec /fullpath/foo.desktop gives me a Permission denied message, even if I change ownership to myself. If I make executable and do the same command, the terminal tab I'm using simply closes (I'm guessing it crashes). Finally, if I do sudo exec /fullpath/foo.desktop, I get an error reporting sudo: exec: command not found.

That's my question, how can I run a foo.desktop file from the terminal?

Best Answer

  • Modern Answer

    gtk-launch <app-name> - where <app-name> is the file name of the .desktop file, with or without the .desktop extension.

    See another answer on this thread for more details. I got this info from that answer.

    Deprecated shell tools answer

    Written a long time ago - see the comments below this answer as to why this approach won't work for many desktop files.

    The command that is run is contained inside the desktop file, preceded by Exec= so you could extract and run that by:

    $(grep '^Exec' filename.desktop | tail -1 | sed 's/^Exec=//' | sed 's/%.//' | sed 's/^"//g' | sed 's/" *$//g') &

    To break that down

    grep  '^Exec' filename.desktop    - finds the line which starts with Exec
    | tail -1                         - only use the last line, in case there are multiple
    | sed 's/^Exec=//'                - removes the Exec from the start of the line
    | sed 's/%.//'                    - removes any arguments - %u, %f etc
    | sed 's/^"//g' | sed 's/" *$//g' - removes " around command (if present)
    $(...)                             - means run the result of the command run here
    &                                 - at the end means run it in the background

    You could put this in a file, say ~/bin/deskopen with the contents

    $(grep '^Exec' $1 | tail -1 | sed 's/^Exec=//' | sed 's/%.//' | sed 's/^"//g' | sed 's/" *$//g') &

    Then make it executable

    chmod +x ~/bin/deskopen

    And then you could do, e.g.

    deskopen /usr/share/applications/ubuntu-about.desktop

    The arguments (%u, %F etc) are detailed here. None of them are relevant for launching at the command line.