Ubuntu – Launch a program keeping focus on terminal

12.04bashcommand line

I'm making a script that combines taking input from the command line with the launch of other programs. So the script will go like this:

...
launch program
Read input from the terminal
...

The problem is that when I launch the program (even if I launch it in the background), the terminal looses focus and the launched program becomes active.

How do I launch a program keeping the focus on the terminal with a default Ubuntu command?

Thank you

Best Answer

If you know the title of the terminal, you can switch back to it after opening the program using the wmctrl command (it doesn't even look like the new program was in the foreground at all if the window opens instantly and you don't need the sleep command):

wmctrl -a <WIN-TITLE>

<WIN-TITLE> doesn't have to be the full title, for example, if the title was TESTING, TEST would work.

Depending on how long it takes to open the program, you might need to use the sleep command to delay the switch back to the terminal. You can use it like this: sleep <SECONDS>s.

To set the title of the terminal from within a script, use:

NAME="NEW_TITLE"; echo -en "\033]0;$NAME\a"

See this answer for more information.

For example, here is a little script to open a program in the background:

NAME="Opening program..."; echo -en "\033]0;$NAME\a"
$1&
sleep 0.75s
wmctrl -a "Opening program"