5

I would like to get output from

xdotool getactivewindow getwindowgeometry --shell

to local variables in bash.

Thought I might could do something like:

declare -A wp=( $(xdotool getactivewindow getwindowgeometry --shell | \
sed 's/\(^[^=]*\)/[\1]/') )

# sub gives:

# [WINDOW]=48926121
# [X]=366
# [Y]=96
# [WIDTH]=819
# [HEIGHT]=1022
# [SCREEN]=0

But this fails with

must use subscript when assigning associative array

another way is to declare local all known values of output and use eval. A safer is to grep, sed or the like six times for each of the values.

Both of these seems very wonky. Is there a better way? Some way to do it in one swoop?

Jeff Schaller
  • 66,199
  • 35
  • 114
  • 250
user376930
  • 53
  • 2
  • What do you mean by local variables? They only exist inside functions. What do you mean by "sub gives"? Is that the output of your command? – jesse_b Oct 12 '19 at 17:38
  • Oh, I see, you want to load `xdotool --shell` output into an associative array instead of just eval'ing it flat as described in the manpage. – frostschutz Oct 12 '19 at 17:58
  • It works the way you wrote but you still need eval for the subscript to be treated as such. – frostschutz Oct 12 '19 at 18:05
  • related: [JSON array to bash variables using jq](https://unix.stackexchange.com/questions/413878/json-array-to-bash-variables-using-jq) – cas Oct 13 '19 at 04:12

1 Answers1

2

If a loop-based solution is acceptable, then you could do

declare -A wp
while IFS='=' read -r name value; do 
  wp+=([$name]=$value)
done < <(xdotool getactivewindow getwindowgeometry --shell)

Ex.

$ declare -A wp
$ while IFS='=' read -r name value; do 
    wp+=([$name]=$value)
  done < <(xdotool getactivewindow getwindowgeometry --shell)

$ for name in "${!wp[@]}"; do 
    printf 'Value of %s is %s\n' "$name" "${wp[$name]}"
  done
Value of WINDOW is 81788935
Value of WIDTH is 1440
Value of SCREEN is 0
Value of X is 0
Value of HEIGHT is 866
Value of Y is 34
steeldriver
  • 78,509
  • 12
  • 109
  • 152