29

My program requires an environment variable as part of one of its parameters:

myprogram --folder=$HOME/.special

However, if I put this into a .desktop file's exec line, it doesn't work:

Exec=myprogram --folder=$HOME/.special

The $HOME seems to resolve to nothing.

Scott Ritchie
  • 1,786
  • 1
  • 13
  • 12

1 Answers1

43

By default environment variables do not seem to be resolved by all implementations, however you can instead exec sh, which will resolve the passed environment variable. Note that the desktop spec also requires you to escape the = and $ character with a backslash. So you want:

Exec=sh -c "myprogram --folder\=\$HOME/.special"

For the full list of characters that need escaping, see the specification

Scott Ritchie
  • 1,786
  • 1
  • 13
  • 12
  • 2
    When your characters are in the string, you do not need to escape any characters. – ggg Nov 28 '12 at 05:54
  • 1
    I need to try this trick, but I love it. Here is an IMO slightly more readable version of the spec, https://developer.gnome.org/desktop-entry-spec/#exec-variables . – dragon788 Jun 29 '17 at 23:54
  • 2
    This worked perfectly for my use-case, which was predeclaring a variable before the command was run: `Exec=sh -c "FOO='bar' /path/to/exec"` – Alex Hart Apr 18 '19 at 11:16
  • 1
    Nice work! I prefer using `bash` instead of `sh`, but it's pretty much the same thing. Here's the bash version: `Exec=bash -c "myprogram --folder=$HOME/.special"`. – Gabriel Staples Feb 11 '20 at 03:51
  • 1
    You could use `exec` to avoid having an additional shell process running: `Exec=sh -c "exec myprogram --folder=$HOME/.special"`. – kelvin Apr 13 '20 at 13:53
  • 2
    It works for `Exec`, but it doesn't work for values `Path` or `Icon`. – Juan José Melero Gómez Jun 01 '20 at 07:08
  • What id you already have an Exec for the .desktop program like `Exec=/home/coyote/anaconda3/bin/spyder %F` but then I want also `Exec=sh -c "LD_LIBRARY_PATH\=/usr/local/lib/:\$BOOST/lib:\$LD_LIBRARY_PATH:/usr/lib/x86_64-linux-gnu/hdf5/serial"` – Brian Wiley Dec 19 '20 at 04:58
  • More definitive description of the Exec key: https://specifications.freedesktop.org/desktop-entry-spec/latest/ar01s07.html – Fonant Jul 27 '22 at 11:06