0

I'm trying to write a script which will check if gnome-terminal is already open, switch to it if it is, or open it if it doesn't.

# check if terminal is running
EXISTS=$(pgrep gnome-terminal)

# if exists is a number
if [[ $EXISTS =~ ^[0-9]+$ ]]; then
    # switch to it
    wmctrl -a gnome-terminal
    echo "Switched to terminal"
else
    # else start it
    gnome-terminal
    echo "Started terminal"
fi

Nothing happens when I run this. It's difficult to test because the terminal is always open if I'm in there trying to do things.

Any ideas what I'm doing wrong? or is there a better way to go about this?

tripleee
  • 175,061
  • 34
  • 275
  • 318
William
  • 77
  • 8
  • 1
    what do you mean `nothing happens`? neither of the `echo` calls is performed? the 'wrong' `echo` call is performed? the 'right' `echo` call is performed but the associated command is not invoked? something else? – markp-fuso Nov 20 '22 at 23:22
  • Sorry, I wasn't clear. I have this bound to a keyboard shortcut & nothing happens when I use that. When I run it from the terminal, the terminal is obviously open, and the 'right' echo is performed. I'm assuming the wmctrl -a call is also correctly performed as it works on other windows besides gnome-terminal. when I'm typing stuff into the terminal though, it's the active window so I can't see it switch. – William Nov 21 '22 at 00:04
  • you should use `if pgrep gnome-terminal; then ...` – Diego Torres Milano Nov 21 '22 at 01:48
  • Send your echo statements to a file to see if the keyboard binding is working. – Nic3500 Nov 21 '22 at 02:01
  • *>It's difficult to test because the terminal is always open if I'm in there trying to do things.* Use another terminal emulator for debugging, e.g. `xterm` – dimich Nov 21 '22 at 05:37
  • `pgrep` basically tells you whether any user is running `gnome-terminal`. Probably instead try to check if any of the existing windows in the current session are `gnome-terminal` ones... or maybe just run `wmctrl -a gnome-terminal` and if it fails, fall back to opening a terminal (not familiar enough with `wmctrl` to know if it's properly written; maybe file a bug report if not). – tripleee Nov 24 '22 at 10:57
  • In other words, does this work? `wmctlrl -a gnome-terminal || gnome-terminal` – tripleee Nov 24 '22 at 10:59

0 Answers0