GTK commands in a single BASH shell script, is it possible?

Solution 1:

There are no "GTK commands" in the way there are GTK+ functions in Python. GTK+ is a library with bindings in several languages, but it doesn't have executable commands for the functions it provides. You can try to do parts of what the GTK+ API can do via some external commands:

  • zenity, yad, etc. for showing dialog boxes
  • xsel or xclip to access the clipboard
  • wmctrl for controlling application windows

But the vast majority of GTK+ functionality can't be accessed by commands.

Solution 2:

Shells are just command interpreters as per POSIX definition. Gtk is a library, and meant to be imported in actual programming languages. So the answer is no, you can't use full-blown Gtk stuff in shell scripts, only the limited set of things that yad and zenity allow.

But you can use Python. It's a scripting language, yet more suitable for system and programming stuff than shells. You can call commands stored in places like /bin or /usr/bin via subprocess module in Python. I've done so many times for my Gtk apps.

Here's for example a standard function I use for calling external commands from Python script:

def run_cmd(self, cmdlist):
    """ Reusable function for running external commands """
    new_env = dict(os.environ)
    new_env['LC_ALL'] = 'C'
    try:
        stdout = subprocess.check_output(cmdlist, env=new_env)
    except subprocess.CalledProcessError:
        pass
    else:
        if stdout:
            return stdout

And here's an example using it in my xrandr-indicator for switching screen resolution from Ubuntu's top panel; as the name suggests, it calls xrandr behind the scenes :

    self.run_cmd(['xrandr','--output',out,'--mode',mode]) 

As for shell, you'd need to call a shell with -c argument. So something like this could work:

subprocess.Popen(['bash','-c', 'echo hello world'])

Alternatively, consider implementing interprocess communication. Make GUI in python, but let it communicate with a shell script via named pipe or file.