How do you add/remove applications to/from the Unity Launcher from command line?

I am customizing an Ubuntu 14.04 Live CD with UCK (Ubuntu Customization Kit). The program gives you a chroot environment in a terminal to make changes.

I want to add and remove what programs appear on the dock.

I'm not sure if this can be accomplished by modifying the .desktop file?

How can this be done using the terminal?


The script below can be used to either add or remove items to the launcher, depending on the argument(s):

#!/usr/bin/env python3

import subprocess
import sys

desktopfile = sys.argv[1]

def current_launcher():
    get_current = subprocess.check_output(["gsettings", "get", "com.canonical.Unity.Launcher", "favorites"]).decode("utf-8")
    return eval(get_current)

def set_launcher(desktopfile):
    curr_launcher = current_launcher()
    last = [i for i, x in enumerate(curr_launcher) if x.startswith("application://")][-1]
    new_icon = "application://"+desktopfile
    if sys.argv[2] == "a":
        if not new_icon in curr_launcher:
            curr_launcher.insert(last, new_icon)
            subprocess.Popen(["gsettings", "set", "com.canonical.Unity.Launcher","favorites",str(curr_launcher)])
    elif sys.argv[2] == "r":
        curr_launcher.remove(new_icon)
        subprocess.Popen(["gsettings", "set", "com.canonical.Unity.Launcher","favorites",str(curr_launcher)])

set_launcher(desktopfile)

How to run it

  1. Paste the code into an empty file, save it as set_launcher.py
  2. Run it by the command:

    python3 /path/to/set_launcher.py <name_of_.desktop_file> a
    

    to add an icon, or:

    python3 /path/to/set_launcher.py <name_of_.desktop_file> r
    

    to remove an icon

    Example:

    python3 /path/to/set_launcher.py gedit.desktop a
    

    to add gedit to the launcher, or

    python3 /path/to/set_launcher.py gedit.desktop r
    

    to remove gedit from the launcher

Explanation

The list of launcher icons is defined in the key:

com.canonical.Unity.Launcher favorites

and can be fetched by the command:

gsettings get com.canonical.Unity.Launcher favorites

to set an alternative list (given the fact you use the correct format):

gsettings set com.canonical.Unity.Launcher favorites "[item1, item2, etc]"

Can you achieve this by editing a .desktop file?

No, it has nothing to do with the file itself. What matters is that the file either is in the list of launcher favourites or not.

Editing this list from command line is exactly what the script does.