I am writing a script that prompts the user for input and does some processing afterwards. I was using read
to get the data, but then I noticed that when the script is ran with a keyboard shortcut (I added an entry in Ubuntu's Keyboard Shortcut list) it ignores the read
and continues with the rest of the code.
How can I read user input with a script running in the background like this?
Best Answer
If I understand correctly, you're running the script directly from a GUI environment, not from inside a terminal.
The terminal is what provides the script a way to receive input. If you run the script from the GUI via a menu entry or a keyboard shortcut, the script's input is connected to nothing (this nothing is called
/dev/null
), so when you ask to read a line, theread
command says that there is nothing to read (end of file).You have two solutions: change the way you call your script, or change your script. The former is simpler and allows your script to be executed inside a terminal sometimes. The latter is more complex but more flexible.
You can easily change your script to run in a terminal. Instead of setting a keyboard shortcut for
/path/to/script
, set a keyboard shortcut forxterm -e /path/to/script
orgnome-terminal -e /path/to/script
or whatever terminal emulator you prefer. The terminal window will appear as soon as you press the key and will disappear when your script terminates.Alternatively, you can change your script to read input through a GUI window instead of from its standard input. Zenity is a common choice for this (there's an Ubuntu package Install zenity http://bit.ly/software-small). Inside your script, you can use
[ -t 0 ]
to test whether it's running in a terminal.