2

I have this script:

#!/bin/bash

declare -a arr
arr+=(
[mirror]="xrandr --output hdmi-1 --same-as edp-1"
[extend]="xrandr --output hdmi-1 --auto"
)
screen=hdmi-1

chosen=$(echo -e ${!arr[@]}| dmenu -fn monospace-14)

[ "$chosen" != "" ] || exit

But when I run this, mirror and extend are the same item.

Is there a way to get this into two separate items?

To print multiple items you do this:

echo -e "first\nsecond\nthird" | dmenu

I used an associative array because then I only need to write the options once, and adding options is very easy (just append the list).

  • Are you wanting to use bash or sh? Your code explicitly uses sh but the question is tagged bash. Please clarify. n. b. I'm pretty sure sh does not have associative arrays. – DopeGhoti Jan 8 at 19:19
  • @DopeGhoti Im using bash. Thats a typo sry – Felix Rosén Jan 8 at 19:23
  • 2
    Shouldn't it be declare -A (upper case) for an associative array (as opposed to declare -a for an indexed array)? – steeldriver Jan 8 at 19:36
  • +1 That is so amazingl! I never heard about declare -A before. I am feeling like a idiot for all scripts that I wrote without knowing about that. So that is the OP's problem. – Luciano Andress Martini Jan 8 at 19:38
0

Use printf instead of echo to format the inputs separated by newlines:

#!/bin/bash

declare -A arr
arr+=(
[mirror]="xrandr --output hdmi-1 --same-as edp-1"
[extend]="xrandr --output hdmi-1 --auto"
)

choice=$(printf "%s\n" "${!arr[@]}" | dmenu -fn monospace-14)

# Execute choice if dmenu returns ok:
[ $? = 0 ] && ${arr[$choice]}

Note that declare -a is for just an indexed array while declare -A is for an associative array. The quotes around the printf arguments let you use keys that include space characters.

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.