Arrays
An array can hold several values under one name. Array naming is the same as variables naming.
An array can hold several values under one name. Array naming is the same as variables naming. An array is initialized by assign space-delimited values enclosed in ()
my_array=(apple banana "Fruit Basket" orange)
new_array[2]=apricotArray members need not be consecutive or contiguous. Some members of the array can be left uninitialized.
The total number of elements in the array is referenced by ${#arrayname[@]}
my_array=(apple banana "Fruit Basket" orange)
echo ${#my_array[@]} # 4The array elements can be accessed with their numeric index. The index of the first element is 0.
my_array=(apple banana "Fruit Basket" orange)
echo ${my_array[3]} # orange - note that curly brackets are needed
# adding another array element
my_array[4]="carrot" # value assignment without a $ and curly brackets
echo ${#my_array[@]} # 5
echo ${my_array[${#my_array[@]}-1]} # carrotExercise
Try it
Expected output
1 2 3
hello world
The number of names listed in the NAMES array: 3
The second name on the NAMES list is: EricSolution
#!/bin/bash
NAMES=( John Eric Jessica )
# write your code here
NUMBERS=( 1 2 3 )
STRINGS=( "hello" "world" )
NumberOfNames=${#NAMES[@]}
second_name=${NAMES[1]}
echo ${NUMBERS[@]}
echo ${STRINGS[@]}
echo "The number of names listed in the NAMES array: $NumberOfNames"
echo "The second name on the NAMES list is:" ${second_name}Get the Bash agent pack
A battle-tested AGENTS.md, the review checklist, and the failure-mode cheat sheet for Bash. One email, then occasional updates when the tooling shifts. No course pitch.
AGENTS.md now — no email needed.