Bird
0
0

What is wrong with this Bash code snippet for slicing an array?

medium📝 Debug Q14 of 15
Bash Scripting - Arrays
What is wrong with this Bash code snippet for slicing an array?
arr=(x y z)
echo ${arr:1:2}
AIt will output an empty string
BIt will output only one element instead of two
CIt will cause a syntax error because slicing is not allowed
DIt will output 'y z' correctly
Step-by-Step Solution
Solution:
  1. Step 1: Check slicing syntax correctness

    The code uses ${arr:1:2} without @. For arrays, @ is needed to slice multiple elements.
  2. Step 2: Understand the effect of missing @

    Without @, Bash uses the first element x as a scalar string and slices it from index 1 length 2. Since x has length 1, it outputs an empty string.
  3. Final Answer:

    It will output an empty string -> Option A
  4. Quick Check:

    Missing @ slices first elem as string -> empty [OK]
Quick Trick: Always use @ for array slicing, else string slicing happens [OK]
Common Mistakes:
MISTAKES
  • Omitting @ and expecting array slice
  • Assuming no error but wrong output
  • Confusing string and array slicing syntax

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Bash Scripting Quizzes