Bird
0
0

In Bash, given an array tools=(hammer wrench screwdriver), which command prints the last element without using a fixed index?

easy🧠 Conceptual Q1 of 15
Bash Scripting - Arrays
In Bash, given an array tools=(hammer wrench screwdriver), which command prints the last element without using a fixed index?
Aecho ${tools[-1]}
Becho ${tools[3]}
Cecho ${tools[@]: -1}
Decho ${tools[last]}
Step-by-Step Solution
Solution:
  1. Step 1: Understand negative indexing

    Bash arrays do not support negative indices like Python, so ${tools[-1]} won't work as expected.
  2. Step 2: Use slicing to get last element

    The syntax ${tools[@]: -1} extracts the last element by slicing from the end.
  3. Final Answer:

    echo ${tools[@]: -1} -> Option C
  4. Quick Check:

    Run the command and verify it prints 'screwdriver' [OK]
Quick Trick: Use slicing with space before -1 to get last element [OK]
Common Mistakes:
MISTAKES
  • Using negative indices directly like ${tools[-1]}
  • Using an out-of-range fixed index like ${tools[3]}
  • Trying to use undefined variable names like ${tools[last]}

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Bash Scripting Quizzes