= Associative array ! Apostolos rootApostolos@swarmlab.io // Metadata: :description: Intro and Install :keywords: Linux, apt :data-uri: :toc: right :toc-title: Πίνακας περιεχομένων :toclevels: 4 :source-highlighter: highlight :icons: font :sectnums: {empty} + .NOTE [NOTE] ==== Assuming you're already logged in ==== == Associative array, dictionary or map === Exercise - vim testfile.sh - copy-paste - chmod +x ./testfile.sh - ./testfile.sh [source,bash] ---- #!/bin/bash bash --version # Must be at least version 4 to have associative arrays declare -A array=( [1,0]="first name" [1,1]="second name" [2,0]="third name" [3,0]="foo bar" [test 1]="test bar" ) var=$(cat < ${array[$i]}"; done "result: " EOF for i in "${!array[@]}"; do echo "$i => ${array[$i]}"; done echo "" echo "" cat <<'EOF' ---------------------------------------------------------- for with ${!array[@]} ---------------------------------------------------------- for i in ${array[@]}; do echo "$i => ${array[$i]}"; done "result: " EOF for i in ${array[@]}; do echo "$i => ${array[$i]}"; done echo "" echo "" cat <<'EOF' ---------------------------------------------------------- for with "${!array[*]}" ---------------------------------------------------------- for i in "${!array[*]}"; do echo "$i => ${array[$i]}"; done "result: " EOF for i in "${!array[*]}"; do echo "$i => ${array[$i]}"; done echo "" echo "" cat <<'EOF' ---------------------------------------------------------- for with ${!array[*]} ---------------------------------------------------------- for i in ${!array[*]}; do echo "$i => ${array[$i]}"; done "result: " EOF for i in ${!array[*]}; do echo "$i => ${array[$i]}"; done echo "" echo "" cat <<'EOF' ---------------------------------------------------------- we can get the value of the '1,0' key as array ---------------------------------------------------------- declare -a names=(${array[1,0]}) EOF declare -a names=(${array[1,0]}) echo "" echo "" cat < ${array[$i]}"; done ---- === create from array [source,bash] ---- declare -a names=(${array[1,0]}) ---- === test [source,bash] ---- if [ ${array[1,0]+_} ]; then echo "Found"; else echo "Not found"; fi ---- === indexing [source,bash] ---- KEYS=("${!array[@]}") echo ${array[${KEYS[0]}]} ---- === unset key [source,bash] ---- unset array["test 1"] ---- === unset all [source,bash] ---- unset array ----