Challenge - 5 Problems
Array Length Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 Command Output
intermediateWhat is the output of this Bash script?
Consider the following Bash script that defines an array and prints its length. What will be the output?
Bash Scripting
arr=(apple banana cherry date)
echo ${#arr[@]}Attempts:
2 left
💡 Hint
Remember that ${#array[@]} gives the number of elements in the array.
✗ Incorrect
The array 'arr' has 4 elements: apple, banana, cherry, and date. Using ${#arr[@]} returns the count of elements, which is 4.
💻 Command Output
intermediateWhat does this script print?
Given this Bash script, what is the output?
Bash Scripting
arr=(one two three)
echo ${#arr}Attempts:
2 left
💡 Hint
${#arr} returns the length of the first element, not the number of elements.
✗ Incorrect
${#arr} without [@] or [0] returns the length of the first element of the array, which is 'one' with 3 characters.
💻 Command Output
advancedWhat is the output of this Bash script with sparse array?
Consider this Bash script where an array has elements assigned at non-contiguous indices. What will be the output?
Bash Scripting
arr=() arr[0]=zero arr[3]=three arr[5]=five echo ${#arr[@]}
Attempts:
2 left
💡 Hint
Array length counts the number of elements, not the highest index.
✗ Incorrect
The array has elements at indices 0, 3, and 5, so total 3 elements. ${#arr[@]} returns 3.
💻 Command Output
advancedWhat does this script output when printing array length?
What is the output of this Bash script?
Bash Scripting
arr=(a b c d e)
length=${#arr[@]}
echo $length
unset arr[2]
echo ${#arr[@]}Attempts:
2 left
💡 Hint
Unsetting an element removes it, reducing the count.
✗ Incorrect
Initially, the array has 5 elements. After unsetting index 2, the element is removed, so length becomes 4.
💻 Command Output
expertWhat is the output of this Bash script with indirect reference?
Given this script, what will be the output?
Bash Scripting
arr=(x y z)
name=arr
echo ${#name[@]}
echo ${#arr[@]}Attempts:
2 left
💡 Hint
Variable name is a string, not an array reference.
✗ Incorrect
${#name[@]} returns 1 because 'name' is a string variable, not an array. ${#arr[@]} returns 3.
