0
0
Bash Scriptingscripting~10 mins

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

Choose your learning style9 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.