Skip to content

Instantly share code, notes, and snippets.

@Qkessler
Created February 12, 2022 19:17
Show Gist options
  • Save Qkessler/02eda7644e0d77b3134bdc26518c65c1 to your computer and use it in GitHub Desktop.
Save Qkessler/02eda7644e0d77b3134bdc26518c65c1 to your computer and use it in GitHub Desktop.
open-or-bring-to-front is a command line script to be run with some custom keybinding attached to it. It launches the application passed as <launch-command> (see Usage below) if the application hasn't already a window open, which matches with <search-string>. If it does, it brings all the windows of said application to front.
#!/bin/bash
# open-or-bring-to-front
#
# open-or-bring-to-front is a command line script to be run with
# some custom keybinding attached to it. It launches the application
# passed as <launch-command> (see Usage below) if the application hasn't
# already a window open, which matches with <search-string>.
# If it does, it brings all the windows of said application to front.
#
# The difference with other versions I found is that it supports
# having a name to search for that is different from the "terminal"
# command to be run.
#
# It depends on "xdotool" so be sure to have it installed and somewhere
# in your path. An installation command using Ubuntu could be:
#
# sudo apt install xdotool
#
# That said, open-or-bring-to-front works as follows:
#
# open-or-bring-to-front <search-string> <launch-command>
#
# Examples (yes, same name works too):
#
# - open-or-bring-to-front terminal gnome-terminal
# - open-or-bring-to-front edge-beta microsoft-edge-beta
# - open-or-bring-to-front spotify spotify
prog="$1"
launch="$2"
activate_all_windows() {
for pid in $windows; do
xdotool windowactivate $pid
done
}
logic_with_server() {
number_windows="$(echo $windows | wc -w)"
if [[ $number_windows -lt 2 ]]; then
$launch &
windows="$(xdotool search --desktop 0 $prog)"
fi
activate_all_windows
exit
}
windows="$(xdotool search --desktop 0 $prog)"
case $prog in
emacs)
logic_with_server
;;
spotify)
logic_with_server
;;
*)
if [ -z "$windows" ]; then
$launch &
windows="$(xdotool search --desktop 0 $prog)"
fi
activate_all_windows
exit
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment