3

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?

  • 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 – cas Oct 13 '19 at 4:12
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
| improve this answer | |
  • wp["$name"]="$value" also works. i.e. += isn't required. – cas Oct 13 '19 at 4:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.