How would a
bash script know if it has been launched by a
.desktop file, and how would it know the path of that launcher?
Extra Points: How would I extract the
"comment" field of that
.desktop file - to be used within the script?
The environment variable
GIO_LAUNCHED_DESKTOP_FILE contains the path to the
.desktop file, and
GIO_LAUNCHED_DESKTOP_FILE_PID contains the process ID of the program originally invoked by the
.desktop file. You need to check the PID, otherwise you might incorrectly believe the script to have been invoked by a desktop file, whereas it was actually invoked by a program invoked by a program invoked by a program invoked by the desktop file.
if [ -n "$GIO_LAUNCHED_DESKTOP_FILE" ] && [ "$$" -eq "$GIO_LAUNCHED_DESKTOP_FILE_PID" ]; then echo "I was invoked by $GIO_LAUNCHED_DESKTOP_FILE" else echo "I wasn't invoked by a .desktop file" fi
This may not work in all applications or in all environments, because this environment variable didn't exist back when
.desktop files were introduced, it might not be supported everywhere yet. Gnome applications should all work since the job is done in the Glib library.
Note that if the desktop file has
Terminal=true, the environment variable may not end up being set, if the terminal emulator has a single process that runs all instances rather than one process per instance. That's how Gnome-terminal works, for example. The same applies if you explicitly run
gnome-terminal … as the command in the desktop file. Terminal emulators that run one process per terminal, such as xterm, will work fine.
I'm not aware of any shell tool to parse desktop files. You can use ordinary tools such as grep, sed, awk and so on, but you'll have to handle things like backslash escapes and per-language entries (or choose not to support them). Here's a script that extracts the comment in the simple case (no backslashes, default language).
if [ -n "$GIO_LAUNCHED_DESKTOP_FILE" ] && [ "$$" -eq "$GIO_LAUNCHED_DESKTOP_FILE_PID" ]; then comment=$(<"$GIO_LAUNCHED_DESKTOP_FILE" sed -n 's/^Comment=//p') if [ -n "$comment" ]; then echo "I was invoked by $GIO_LAUNCHED_DESKTOP_FILE with the following comment:" echo "$comment" else echo "I was invoked by $GIO_LAUNCHED_DESKTOP_FILE with no comment" fi else echo "I wasn't invoked by a .desktop file" fi