1

I need to run a bash script that will retrieve all of the desktop files located in a specific menu item (like accessories/utilities or education, etc) and then run a specific one of them. What terminal commands can I use to do this?

dessert
  • 39,982
tristo
  • 113
  • 3

1 Answers1

0

The .desktop files are located under either /usr/share/applications/ (system wide) or ~/.local/share/applications (per user). The categorisation is done by setting the “Categories” property in the file and this may not be the exact same as shown in the menu, so you first need to find out the correct category name. In my menu there’s a category called “Büro”, which is the German term for “Office”, and it contains a launcher for qpdfview. To review the .desktop file’s “Categories” line I run:

$ grep Categories /usr/share/applications/qpdfview.desktop 
Categories=Viewer;Office;

That shows the two categories for the program, so it’s called “Office” in the .desktop files. To get a list of every .desktop file categorised with “Office” I use grep again, with the -l flag to only show filenames without matches:

$ grep -l Categories.*Office /usr/share/applications/*
/usr/share/applications/evince.desktop
/usr/share/applications/evince-previewer.desktop
/usr/share/applications/gnucash.desktop
/usr/share/applications/libreoffice-base.desktop
/usr/share/applications/libreoffice-calc.desktop
/usr/share/applications/libreoffice-draw.desktop
/usr/share/applications/libreoffice-impress.desktop
/usr/share/applications/libreoffice-math.desktop
/usr/share/applications/libreoffice-startcenter.desktop
/usr/share/applications/libreoffice-writer.desktop
/usr/share/applications/qpdfview.desktop

So that’s our list of office programs, now to run them I’d simply use xdg-open, e.g.:

xdg-open /usr/share/applications/qpdfview.desktop

If xdg-open doesn’t work on your system you may also just extract the start command from the file and run it directly, e.g.:

exec $(grep -Po 'Exec=\K[^ ]*' /usr/share/applications/qpdfview.desktop)

You didn’t provide information on how you or the script’s user should choose the program to run, so here are some links that may help you with that:

Saving the filenames in an array for easy processing in a script is as easy as that:

options=("$(grep -l Categories.*Office /usr/share/applications/*)")
dessert
  • 39,982