Friday, April 29, 2016

Bash Toggle Process Function/Script


Bash Toggle Process Function/Script



If you use both Windows and Linux and like automation tools then you know that compared to Windows, Linux can be somewhat lacking. Not that Linux isn't powerful or capable of something like AutoIt or AutoHotkey (AutoKey for Linux), but with AutoHotkey in Windows there's really nothing I can't do, whereas Autokey is very, very limited by just using Python.

Having said that, you can still do lots of stuff with AutoKey by using other scripting languages, especially just by having AK executing good 'ol shell scripts. Today I want to show you a 'toggle process' bash script (easily made universal) I wrote to use with AutoKey (AK not necessary though). This script has 3 modes: 1. Run if not running, 2. Activate if not active, and 3. Minimize if active. The only thing this does not do is close the process (you have alt+f4 for that :D) and things like window shading of course...

Usage

To use this script all you would have to do is either write a script or run in a terminal eg.:
toggle firefox
and firefox will either start, activate or minimize depending on its' state. If your process is not in a normal bin path that your shell looks in the you must provide the full path e.g.:
toggle /full/path/to/your/process

Dependencies

This script/function is depenedent on Linux packages 'xprop' and 'xdotools', both of which come pre-installed on most modern day Linux distrobutions, but if not I can almost garauntee you can find the packages for your distro in your package manager.
This has been tested and running on both Ubuntu and Opensuse.
Either copy the below code or there's a downloadable script below.

Source Code

Function (for use in .bash_aliases for example)

function toggle {
  if [[ -z "$1" ]]; then
   echo "No process given."
  else
   cpid=$(xdotool search --name $1)
   if [[ -z "$cpid" ]]; then
      $1 &
   else
      for i in $cpid; do
         cstate=$(xprop -id $i | grep "HIDDEN")
     if [[ -z "$cstate" ]]; then
            xdotool windowminimize $i
         else
            xdotool windowactivate $i
         fi
      done
   fi
  fi
}

Script (for use everywhere else)

#!/bin/bash
if [[ -z "$1" ]]; then
 echo "No process given."
else
 cpid=$(xdotool search --name $1) 
 if [[ -z "$cpid" ]]; then
    $1 & 
 else
    for i in $cpid; do
       cstate=$(xprop -id $i | grep "HIDDEN")
   if [[ -z "$cstate" ]]; then
          xdotool windowminimize $i
       else
          xdotool windowactivate $i
       fi
    done
 fi
fi

Download Script

Toggle Shell Script

No comments: