Is there a simpler way to find the name of the screen holding the mouse in bash

Viewed 143

I have made a script to get the name of the screen holding the mouse using xdotool for mouse location and xrandr for the screen setup. Is there a simpler way of doing it, either by built-in function or by altering my script

#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'

## Get mouse positions and save directly to variables X/Y
eval $(xdotool getmouselocation --shell)

### get connected and active screen sizes/placements
### regex matches format e.g. 1920x1080+0+0
screens=$(xrandr | grep -oP '^\w+.* (\d+x\d+\+\d+\+\d+)')

## Loop through screens and see if mouse position is within the screen
for screen in $screens
do
    name=$(echo "$screen" | grep -oP "^\w+")
    scr_info=$(echo $screen | awk '{print $NF}')

    # Extract screen width/height and offset
    screen_w=$(echo $scr_info | awk -F '[x+]' '{print $1}')
    screen_h=$(echo $scr_info | awk -F '[x+]' '{print $2}')
    screen_x=$(echo $scr_info | awk -F '[x+]' '{print $3}')
    screen_y=$(echo $scr_info | awk -F '[x+]' '{print $4}')

    # Check if mouse coord is within screen
    if [ "$X" -ge "$screen_x" ] && [ "$X" -lt "$(( screen_x + screen_w))" ] &&
       [ "$Y" -ge "$screen_y" ] && [ "$Y" -lt "$(( screen_y + screen_h))" ]
    then
        echo "$name"
    fi
done
1 Answers

By reducing the amount of times awk command is used, your script will definitely run faster.

Another way to improve performance is by using grep more often, since it will most likely be faster than awk in several scenarios.

On the excerpt below we will use grep to filter the resolution and position from the xrandr string, and a single awk command to make an array.

scr_info=($(echo $screen | grep -Po '\d{0,5}x\d{0,5}\+\d{0,5}\+\d{0,5}' | awk -F '[x+]' '{print $1"\n"$2"\n"$3"\n"$4}'))
   
screen_w="${scr_info[0]}"
screen_h="${scr_info[1]}"
screen_x="${scr_info[2]}"
screen_y="${scr_info[3]}"
Related