Arrays and Dictionaries Flashcards
How do you define the entire array automatically using a file?
readarray -t myArr < sample.txt
echo ${myArr[0]} #Index 0 of the array will contain the first line of sample.txt
echo ${myArr[1]} #Index 1 of the array will contain the second line of sample
More ways: https://linuxopsys.com/bash-readarray-with-examples
How do you define the entire array explicitly like assigning a variable?
Fruits=(‘Apple’ ‘Banana’ ‘Orange’)
Printing array entries?
echo “Method 1:”
for i in ${myArr[@]}
do
echo $i
done
echo “Method 2:”
for (( i=0; i<${#myArr[@]}; i++ ))
do
echo ${myArr[$i]}
done
Method 3:
echo “${Fruits[@]}”
all elements; space separated
Print a single entry in an array:
echo ${myArr[0]}
where 0 is the first entry
Printing the last element in an array
echo “${Fruits[-1]}”
print the number of elements
echo “${#Fruits[@]}”
print the
string length of the 1st
element
echo “${#Fruits}”
print the
string length of the nth
element
echo “${#Fruits[3]}”
print the range from position 3, length 2
echo “${Fruits[@]:3:2}”
Keys of all elements, space-separated
echo “${!Fruits[@]}”
Array Operations
Fruits=(“${Fruits[@]}” “Watermelon”) # Push
Fruits+=(‘Watermelon’) # Also Push
Fruits=( “${Fruits[@]/Ap*/}” ) # Remove by regex match
unset Fruits[2] # Remove one item
Fruits=(“${Fruits[@]}”) # Duplicate
Fruits=(“${Fruits[@]}” “${Veggies[@]}”) # Concatenate
lines=(cat "logfile"
) # Read from file
Defining an array as a dictionary
declare -A sounds
declares “sounds” as a dictionary object
How does a
dictionary (associative arrays)
differ from a normal array?
Arrays are numerical starting with element 0,1, … N
Dictionaries aka associative arrays have a keys/values association instead of numerical/elements.
Give an example of a dictionary (associative array)
sounds[dog]=”bark”
sounds[cow]=”moo”
sounds[bird]=”tweet”
sounds[wolf]=”howl”
Example use of calling one Dictionary entry:
set entry:
sounds[dog]=”bark”
example call:
echo “${sounds[dog]}”
would print:
bark