Skip to content

Instantly share code, notes, and snippets.

@localhost
Created October 17, 2021 11:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save localhost/88035833f20b662c40b2f0b3966b7a1a to your computer and use it in GitHub Desktop.
Save localhost/88035833f20b662c40b2f0b3966b7a1a to your computer and use it in GitHub Desktop.
Center and optionally resize a window (X11)
#!/usr/bin/env bash
# uses wmctrl and xdotool
#
# improved upon the solutions listed in
# https://askubuntu.com/questions/104155/center-a-window-via-command-line
if [[ "$1" == "-h" || "$1" == "--help" ]]; then
echo "Usage: $0 \"window name\" [ WxH ]"
exit 0
fi
# use active window by default
if [[ $# -eq 0 || "$1" == "" ]]; then
wn=$(xdotool getactivewindow getwindowname)
else
wn="$1"
fi
# get desktop size
IFS='x' read sw sh < <(xdpyinfo | grep dimensions | grep -o '[0-9x]*' | head -n1)
# get window size
read wx wy ww wh < <(wmctrl -lG | grep "$wn" | sed 's/^[^ ]* *[^ ]* //;s/[^0-9 ].*//;')
# optional: use new window size
if [[ $# -eq 2 ]]; then
# IFS='x' read -e -i "$2" ww wh
IFS='x' read ww wh < <(echo "$2")
fi
nx=$(( (sw-ww) / 2 ))
ny=$(( (sh-wh) / 2 ))
# xdotool getactivewindow windowmove "$nx" "$ny"
wmctrl -r "$wn" -e 0,$nx,$ny,$ww,$wh
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment