Bird
0
0

Given a Bash array nums=(1 2 3 4 5 6), how do you remove all even numbers using array filtering?

hard🚀 Application Q9 of 15
Bash Scripting - Arrays
Given a Bash array nums=(1 2 3 4 5 6), how do you remove all even numbers using array filtering?
Anums=($(for n in "${nums[@]}"; do (( n % 2 != 0 )) && echo $n; done))
Bunset nums[0] nums[2] nums[4]
Cnums=(${nums[@]/2/})
Dnums=(${nums[@]:0:3})
Step-by-Step Solution
Solution:
  1. Step 1: Use a loop to filter elements

    Loop through each element and check if it is odd.
  2. Step 2: Rebuild array with only odd numbers

    Use command substitution to collect odd numbers into new array.
  3. Final Answer:

    nums=($(for n in "${nums[@]}"; do (( n % 2 != 0 )) && echo $n; done)) -> Option A
  4. Quick Check:

    Filter array with loop and condition [OK]
Quick Trick: Use loop and condition to filter array elements [OK]
Common Mistakes:
MISTAKES
  • Trying to unset by fixed indices without checking values
  • Using substitution which only removes first match
  • Slicing array instead of filtering

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Bash Scripting Quizzes