Is there a way to create a function that changes booleans values based off array?

I have different installation prompts in my script that can be toggled by boolean values. Each respective boolean I want to put into a container data-type like a array so that I can categorize & later modify them. More specifically, I want to modify my booleans from within that array/list using a function. Do I have to modify the items using a index value or something instead of the iterable value i? Thanks in advance.

#!/bin/bash
# this is example code based off my installation script.
INSTALL_GIMP=0
INSTALL_KRITA=0
INSTALL_VLC=0
images_array=($INSTALL_GIMP $INSTALL_KRITA $INSTALL_VLC)

enabling_prompts() {
arg1=$1
for i in ${arg1[@]} ; do
    echo "$i"
    i=1
    echo "$i"
done
}
# ^ I want a function like this to change the given array's booleans to 1.
# I want to use modifiable arrays to make it easier when adding 
# -more categorized "programs" to the prompt script.

enabling_prompts $images_array

while [[ $INSTALL_GIMP == 1 ]]
do
echo "This is skeleton code. I need to change the values to 1 so that this code can be run."
done

1 answer

  • answered 2020-07-29 18:18 Léa Gris

    You can store boolean into an associative array and access the array by reference within the function:

    #!/usr/bin/env bash
    
    # Associative array of boolean
    declare -iA images_array=(
      ["gimp"]=0
      ["krita"]=0
      ["vlc"]=0
    )
    
    # The array name is passed by reference as argument 1
    enabling_prompts() {
      # array is a reference name (Need Bash 4.2+)
      local -n array="$1"
      for prog in "${!array[@]}"; do
        printf -v prompt 'Install %s (Y)es|(N)o?\n' "$prog"
        while read -r -p "$prompt" answer; do
          case "$answer" in
            [yY])
              array["$prog"]=1
              break
              ;;
            [nN])
              break
              ;;
            *) :
              ;;
          esac
          :
        done
      done
    }
    
    # ^ I want a function like this to change the given array's booleans to 1.
    # I want to use modifiable arrays to make it easier when adding 
    # -more categorized "programs" to the prompt script.
    
    enabling_prompts 'images_array'
    
    for prog in "${!images_array[@]}"; do
      if [ "${images_array["$prog"]}" -eq 1 ]; then
        printf 'Installing %s...\n' "$prog"
      else
        printf '%s will not be installed!\n' "$prog"
      fi
    done