0

I have tried messing around with a script that sets my display resolutions as i use my laptop with different setups of external monitors. also to learn bash i suppose.

now, i have a associative array with all my monitors configured as keys, and expected resolution as value.

declare -A known_monitor
known_monitor[Virtual1]=1920x1200
known_monitor[Virtual2]=1400x1050
Known_monitor[eDP-1]=2560x1440

when i try to access the monitors like this:

  for monitor in "${monitors[@]}"
  do
    echo ------------------
    echo $monitor
    echo ${known_monitor[$monitor]}
    echo ------------------
  done

I see the $monitor value, but the "known_monitor" is empty.

------------------
eDP-1

------------------

I have tried moving parantheses around and adding citation marks, but nothing seems to work.

Any advice would be helpful, Thanks in advance!

2 Answers2

3

Corrected a few errors in your script and it works:

#!/usr/bin/env bash

declare -A known_monitor
known_monitor[Virtual1]=1920x1200
known_monitor[Virtual2]=1400x1050
known_monitor[eDP-1]=2560x1440

for monitor in "${!known_monitor[@]}"
do
  echo ------------------
  echo "$monitor"
  echo "${known_monitor[$monitor]}"
  echo ------------------
done

Alternate declaration for the known_monitor associative array:

declare -A known_monitor=(
  [Virtual1]=1920x1200
  [Virtual2]=1400x1050
  [eDP-1]=2560x1440
)

What went wrong with your initial script:

  • Problem1:
    Known_monitor[eDP-1]=2560x1440 with an upper-case K refers to a different variable name as in shell, variable names are case-sensitive. This one has not been declared as an associative array.
  • Problem2:
    1. for monitor in "${monitors[@]}" would iterate the values of a monitors array. But nowhere in your script you have defined and populated this monitors array. You have an associative array named known_monitor.
    2. When you iterate the values of an array, you cannot index this array by its values. You need to iterate the index or keys of the array by prepending the name of the array with an exclamation mark !. Like this: for monitor in "${!monitors[@]}"
Léa Gris
  • 17,497
  • 4
  • 32
  • 41
0

Your last known_monitor uses a capital key, it shouldn't :

declare -A known_monitor
known_monitor[Virtual1]=1920x1200
known_monitor[Virtual2]=1400x1050
known_monitor[eDP-1]=2560x1440

monitors=(Virtual1 Virtual2 eDP-1)

for monitor in "${monitors[@]}"
  do
    echo ------------------
    echo $monitor
    echo ${known_monitor[$monitor]}
    echo ------------------
  done
Mohameth
  • 376
  • 2
  • 10