Ubuntu – Bash script cannot run with keyboard shortcut

14.04bashscriptsshortcut-keysunity

I have this script in my /home/username/

And I can run it via terminal with the following code

./script.sh

or

sh script.sh

it works (it has executable permissions)

but I cannot assign it to a keyboard shortcut. I am adding the shortcuts with the "custom shortcut" tab of keyboard shortcuts. And also tried with xbindkeys, too.

What I've tried so far is (added them to command of the shortcut key)

bash "/script.sh"
bash "./script.sh"
bash "home/username/script.sh"
home/username/script.sh
sh "/script.sh"
"/script.sh"
/script.sh
gnome-terminal "/home/username/script.sh

and many more that I can't remember.

Can anyone tell the problem?

Best Answer

To add a script to a keyboard shortcut:

  1. Unless the script is in $PATH (like ~/bin), use the full path to the script, don't use ~ or relative paths.
  2. If you use full path, start (as always) with a slash, e.g.:

    sh /home/username/script.sh
    

    Your example doesn't :)

  3. If your script is executable, just the full path will do:

    /home/username/script.sh
    

    if it isn't, use the preceding language, e.g.:

    sh /home/username/script.sh
    

What is the issue in your examples

In the attempts you show, you either use incorrect paths (home/some_dir is not a valid directory without a starting slash), you use another path then you mean to (/script.sh refers to your root directory) or you use relative paths. None of them will work from a shortcut key.

The same rules apply to Startup Applications by the way.



EDIT

An additional issue in this case:

Your specific case; using an xdotool command in the script

From a comment, we found out the script you run uses an xdotool command, pressing keys:

#!/bin/bash
xdotool keydown Super key w
sleep 0.5 
xdotool keyup Super 

Virtually pressing keys from a shortcut key combination will practically always lead to key- clashes, since the keys you physically press, will be combined with the ones you virtually press.

What to do

One way to avoid the issue is to give your fingers the time to "leave" the keys, to avoid the real keystrokes to be combined with the virtual ones. Even then though, you need to release the shortcut after you pressed them. The script then becomes:

#!/bin/bash
# here we add a little break to give your fingers 
# the opportunity to release the keys
sleep 0.5
xdotool keydown Super key w
sleep 0.5 
xdotool keyup Super

Note

If you are still having the issue, increase the time in line 4 (and only press the shortcut key shortly)