I have a bash script on my desktop called script.sh.

Currently, if I want to execute it, I open a terminal and type ./script.sh, and if I want to stop it, I have to press Ctrl + C

What I'd like to do is bind the script to a key, let's say 7 for example, so that if the script is off, and I press 7, it's turned on, and if it's already on, and I press 7, it's turned off.

I already know how to bind it in keyboard shortcuts to turn it on, but the problem is that pressing the shortcut again only creates another instance of the script, which isn't what I want.

up vote 4 down vote accepted

Assuming your script is executable, you can easily toggle the script with the tiny script below:



if ! pgrep -f "$scriptpath"
    nohup "$scriptpath" &
    pkill -f "$scriptpath"

To use

  1. Copy the code into an empty file, safe it as toggle_scrip.sh
  2. In the line scriptpath='/full/path/to/script', enter the full path to your script (between single quotes).
  3. Make it executable and run it from a shortcut.

In case you need to control multiple scripts, make the path(s) an argument to the snippet above.

  • Doing this closes all processes and logs me out. Is it missing something after the "&"? – Xanimede Sep 6 at 16:44
  • Works great, thanks. – Xanimede Sep 6 at 17:19
  • @Xanimede my pleasure! – Jacob Vlijm Sep 6 at 17:20
  • Nice and clean answer! – Kev Inski Sep 6 at 17:46

I don't think that togggling something this way through a key binding is possible.

However, one option (a bit of a hack, but hey, it works) would be to modify the script, so it can detect another instance of itself running. That way, when you start the second script through the keybinding, you could issue a pkill or something similar, to terminate both the second and first instance of the script.

  • How would I do that? I don't have any scripting experience. – Xanimede Sep 6 at 12:18
  • Why wouldn't that be possible? Just pgrep -f the script, start if not running, kill if it is running. – Jacob Vlijm Sep 6 at 12:22
  • In the key bindings you can add a command but not scripting code. So you would have to bind a script to a key (which the OP has done). In that script you can do what you suggest or, as I proposed, do the same thing in the original script. Unless I have completely misunderstood you? – Frank van Wensveen Sep 6 at 14:53

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.