Bird
Raised Fist0
Bash Scriptingscripting~10 mins

Adding and removing elements in Bash Scripting - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Adding and removing elements
Start with empty array
↓
Add element: array+=("new_element")
↓
Array updated with new element
↓
Remove element: unset 'array[index
↓
Array updated with element removed
↓
End with modified array
Start with an array, add elements using +=, remove elements using unset, then end with the updated array.
Execution Sample
Bash Scripting
arr=()
arr+=("apple")
arr+=("banana")
unset 'arr[0]'
echo "${arr[@]}"
This script adds 'apple' and 'banana' to an array, removes the first element, then prints the remaining elements.
Execution Table
StepCommandArray StateOutput
1arr=()[]
2arr+=("apple")["apple"]
3arr+=("banana")["apple", "banana"]
4unset 'arr[0]'["banana"] (index 1)
5echo "${arr[@]}"["banana"] (index 1)banana
💡 After unset 'arr[0]', index 0 is removed (sparse array), remaining element at index 1; echo "${arr[@]}" prints set elements only.
Variable Tracker
VariableStartAfter 1After 2After 3Final
arr[]["apple"]["apple", "banana"]["banana"]["banana"]
Key Moments - 2 Insights
What happens to indices after unset 'arr[0]'?
Index 0 is removed, 'banana' remains at index 1; indices do not shift (sparse array).
Why does echo print only 'banana'?
${arr[@]} expands to set elements only, skipping unset indices (holes).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 3, what is the array content?
A["apple", "banana"]
B["banana"]
C["apple"]
D[]
💡 Hint
Check the 'Array State' column at step 3 in the execution_table.
At which step is the first element removed?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
Look at the 'Array State' after unset in step 4 in the execution_table.
If we remove 'unset' command, what will echo print at step 5?
A"banana"
B"apple banana"
C"apple"
D""
💡 Hint
Without unset, array keeps both elements as shown in step 3.
Concept Snapshot
Bash arrays can be changed by adding elements with arr+=("value") and removing with unset 'arr[index]'.
Removing an element removes the index-value pair without shifting remaining indices (sparse array).
Use echo "${arr[@]}" to print all set elements, skipping holes.
Remember: unset does not reindex or shift the array.
Full Transcript
This lesson shows how to add and remove elements in a bash array. We start with an empty array. Then we add elements using the += operator. Next, we remove an element using unset with the element's index. Removing does not shift the array indexes, creating a sparse array (hole at index 0). When printing the array with echo and ${arr[@]}, only set elements are shown. This helps understand how bash arrays behave when modified.

Practice

(1/5)
1. Which command correctly adds the element "apple" to the end of a Bash array named fruits?
easy
A. fruits+=("apple")
B. fruits[0]+="apple"
C. fruits.append("apple")
D. fruits.add("apple")

Solution

  1. Step 1: Understand Bash array addition syntax

    In Bash, to add an element to an array, use the syntax array+=("element").
  2. Step 2: Check each option

    fruits+=("apple") uses the correct syntax. Options A, B, and C are invalid Bash syntax for arrays.
  3. Final Answer:

    fruits+=("apple") -> Option A
  4. Quick Check:

    Add element to array = fruits+=("apple") [OK]
Hint: Use += with parentheses to add elements to arrays [OK]
Common Mistakes:
  • Using string concatenation instead of array syntax
  • Using methods like append() which are not Bash
  • Forgetting parentheses around the element
2. Which of the following is the correct syntax to remove the element at index 2 from a Bash array named colors?
easy
A. unset colors[2]
B. remove colors[2]
C. delete colors[2]
D. colors-=2

Solution

  1. Step 1: Recall how to remove array elements in Bash

    Bash uses the unset command with the array element's index to remove it.
  2. Step 2: Verify each option

    unset colors[2] uses unset colors[2], which is correct. Options A, C, and D are not valid Bash commands for removing array elements.
  3. Final Answer:

    unset colors[2] -> Option A
  4. Quick Check:

    Remove element by index = unset colors[2] [OK]
Hint: Use unset with array[index] to remove elements [OK]
Common Mistakes:
  • Using non-existent commands like remove or delete
  • Trying to subtract elements with -= which is invalid
  • Forgetting to specify the index inside brackets
3. What is the output of this Bash script?
items=("pen" "pencil" "eraser")
items+=("marker")
unset 'items[1]'
for item in "${items[@]}"; do
  echo "$item"
done
medium
A. pen marker
B. pen pencil eraser marker
C. pen eraser marker
D. pen pencil marker

Solution

  1. Step 1: Analyze array modifications

    Initial array: ["pen", "pencil", "eraser"]. Then add "marker" at the end: ["pen", "pencil", "eraser", "marker"]. Then remove element at index 1 ("pencil").
  2. Step 2: Determine final array elements

    After removal, array elements are: index 0="pen", index 2="eraser", index 3="marker". Looping over ${items[@]} skips unset indices, so output is "pen", "eraser", "marker" each on a new line.
  3. Final Answer:

    pen eraser marker -> Option C
  4. Quick Check:

    Remove index 1 and add marker = pen, eraser, marker [OK]
Hint: Unset removes element but keeps others; loop skips unset [OK]
Common Mistakes:
  • Assuming unset shifts elements left
  • Expecting pencil to still print
  • Not realizing loop skips unset indices
4. Identify the error in this Bash script that tries to remove the first element from array nums:
nums=(1 2 3 4)
unset nums(0)
echo "${nums[@]}"
medium
A. Array elements must be strings, not numbers
B. Missing quotes around array name in unset
C. Cannot unset elements in Bash arrays
D. Using parentheses instead of brackets in unset

Solution

  1. Step 1: Check unset syntax for array elements

    To remove an element, use unset 'array[index]' with square brackets, not parentheses.
  2. Step 2: Identify the error in the script

    The script uses unset nums(0), which is invalid syntax. It should be unset 'nums[0]'.
  3. Final Answer:

    Using parentheses instead of brackets in unset -> Option D
  4. Quick Check:

    Unset uses brackets, not parentheses [OK]
Hint: Use square brackets [] for array indices in unset [OK]
Common Mistakes:
  • Using parentheses () instead of brackets []
  • Forgetting to quote the unset argument
  • Thinking unset can't remove array elements
5. You have a Bash array tasks=("clean" "cook" "shop" "study"). You want to remove the task "cook" and add "exercise" at the end. Which script snippet correctly does this?
hard
A. tasks.remove("cook") tasks.append("exercise")
B. unset 'tasks[1]' tasks+=("exercise")
C. tasks=("clean" "shop" "exercise" "study")
D. unset tasks[2] tasks+="exercise"

Solution

  1. Step 1: Remove element "cook" at index 1

    Use unset 'tasks[1]' to remove the second element safely.
  2. Step 2: Add "exercise" to the end of the array

    Use tasks+=("exercise") to append the new task.
  3. Final Answer:

    unset 'tasks[1]' tasks+=("exercise") -> Option B
  4. Quick Check:

    Remove by unset and add with += [OK]
Hint: Unset by index, add with += and parentheses [OK]
Common Mistakes:
  • Reassigning whole array losing other elements
  • Using non-Bash methods like remove() or append()
  • Concatenating string instead of array element
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard