Advanced Bash Scripting
Arrays
Remove
In this lesson, you’ll learn two key operations for managing Bash arrays:
- Removing a specific element by its index
- Clearing all elements in one command
Removing a Specific Element by Index
To delete a single entry in a Bash array, use unset
with the array name and the target index:
#!/usr/bin/env bash
declare -a servers=("server1" "server2" "server3")
unset 'servers[1]'
echo "Remaining elements: ${servers[@]}"
Running this script produces:
$ ./removing.sh
server1 server3
Note
Bash does not reindex arrays after removal. The original indices remain, leaving gaps in the sequence.
To view both values and their indices after deletion:
#!/usr/bin/env bash
declare -a servers=("server1" "server2" "server3")
unset 'servers[1]'
echo "Values : ${servers[@]}"
echo "Indices: ${!servers[@]}"
$ ./removing_indices.sh
Values : server1 server3
Indices: 0 2
Clearing All Elements
If you need to empty an array completely, omit the brackets when using unset
:
#!/usr/bin/env bash
declare -a servers=("server1" "server2" "server3")
unset servers
echo "After clearing: ${servers[@]}"
$ ./removing_all.sh
No output appears because the array has been removed.
Warning
Using unset array
deletes the entire variable. You must redeclare it before adding new elements.
Summary of Removal Operations
Operation | Command Usage | Result |
---|---|---|
Remove by index | unset 'array[index]' | Deletes the specified element only |
Clear entire array | unset array | Removes all elements and the variable |
Links and References
Watch Video
Watch video content