0
0
Bash Scriptingscripting~5 mins

Accessing array elements in Bash Scripting - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
How do you define an array in Bash?
You define an array by listing elements inside parentheses, separated by spaces. For example: my_array=(apple banana cherry)
Click to reveal answer
beginner
How do you access the first element of an array named my_array in Bash?
Use the syntax ${my_array[0]} to get the first element because array indexes start at 0.
Click to reveal answer
beginner
What does ${my_array[@]} do in Bash?
It expands to all elements of the array my_array. Useful to loop over or print all items.
Click to reveal answer
beginner
How can you get the number of elements in a Bash array my_array?
Use ${#my_array[@]} to get the count of elements in the array.
Click to reveal answer
beginner
What happens if you try to access an array element with an index that does not exist?
You get an empty string because the element is not set. Bash does not throw an error for out-of-range indexes.
Click to reveal answer
In Bash, how do you access the third element of an array named fruits?
A${fruits(3)}
B${fruits[2]}
C${fruits[3]}
D${fruits[1]}
What does ${my_array[@]} return in Bash?
AAll elements of the array
BThe first element only
CThe length of the array
DThe last element only
How do you find the number of elements in a Bash array colors?
A${colors.size}
B${colors.length}
Clength(colors)
D${#colors[@]}
What will happen if you access ${my_array[10]} but the array has only 3 elements?
AReturns the last element
BThrows an error
CReturns an empty string
DReturns null
Which of these is the correct way to define an array in Bash?
Amy_array=(one two three)
Bmy_array=[one, two, three]
Cmy_array={one two three}
Dmy_array: one, two, three
Explain how to access elements in a Bash array and how indexing works.
Think about how you pick items from a list starting at zero.
You got /3 concepts.
    Describe how to get all elements and the length of a Bash array.
    Consider how you might count or list all items in a shopping list.
    You got /3 concepts.