Adding and Removing Array Elements

Su Suriya Ravichandran Updated 06 Dec 2026
8 min read ·Lesson 99 of 205

Bash arrays have no fixed size. Elements can be appended at the end, placed at the front or in the middle, replaced, and removed while a script runs. Bash provides direct syntax for appending (+=) and removing (unset), and the other operations are built from slices and loops. This lesson covers each operation and explains what happens to the indexes, because removing an element leaves a gap that later code has to cope with.

Appending with +=

The += operator with a parenthesized list adds elements after the last one:

tasks=(build test)
tasks+=(deploy)
tasks+=("send report" cleanup)
declare -p tasks
declare -a tasks=([0]="build" [1]="test" [2]="deploy" [3]="send report" [4]="cleanup")

Any number of elements can be added at once, and quoting works as in the original assignment. Appending inside a loop is the standard way to collect results:

results=()
for f in *.log; do
    results+=("$f")
done

The Parentheses Matter

Without parentheses, += does something different: it appends text to element 0, because the bare array name refers to element 0 (lesson 97):

t2=(build test)
t2+=deploy
declare -p t2
declare -a t2=([0]="builddeploy" [1]="test")

No error is printed, so this mistake can go unnoticed. The same string-append behavior is useful on purpose when it targets a specific element:

t3=(file)
t3[0]+=".txt"
declare -p t3
declare -a t3=([0]="file.txt")

Where += Puts New Elements

+= places new elements after the highest index in use, not at the position given by the number of elements. In a normal array the two are the same, but in a sparse array they are not. Older scripts often append with arr[${#arr[@]}]=value, which uses the count as the index:

q=(a b c)
q[${#q[@]}]=d
declare -p q
declare -a q=([0]="a" [1]="b" [2]="c" [3]="d")

That works for q, but in a sparse array the count points into a gap, or onto an existing element:

s=([0]=a [5]=b)
s[${#s[@]}]=new
declare -p s
s+=(added)
declare -p s
declare -a s=([0]="a" [2]="new" [5]="b")
declare -a s=([0]="a" [2]="new" [5]="b" [6]="added")

The array had 2 elements, so new went to index 2, in the middle. += placed added after index 5, at the end. Use += for appending and the count-based form only when you are sure the array has no gaps.

Adding to the Front

There is no prepend operator. To put an element first, build a new list from the new value followed by all old elements:

q=(start "${q[@]}")
declare -p q
declare -a q=([0]="start" [1]="a" [2]="b" [3]="c" [4]="d")

The quoted "${q[@]}" expands to the old elements, one word each, before the assignment replaces the array. Every element moves up by one index, and any gaps disappear, because the new array is numbered from 0 again.

Inserting in the Middle

To insert at a position, combine two slices (lesson 98): the elements before the position, the new value, and the elements from the position onward.

q=("${q[@]:0:2}" INSERTED "${q[@]:2}")
declare -p q
declare -a q=([0]="start" [1]="a" [2]="INSERTED" [3]="b" [4]="c" [5]="d")

${q[@]:0:2} gives the first two elements and ${q[@]:2} everything from position 2 to the end. Slices count positions among the existing elements, so this also works on a sparse array, and the result is renumbered from 0.

Replacing an Element

Assigning to an index replaces the value stored there and changes nothing else:

q[0]=BEGIN
declare -p q
declare -a q=([0]="BEGIN" [1]="a" [2]="INSERTED" [3]="b" [4]="c" [5]="d")

Removing an Element with unset

unset (lesson 41) removes a single element when it is given an index:

n=(zero one two three four)
unset 'n[1]'
declare -p n
echo "count ${#n[@]} indices ${!n[@]}"
echo "n[1]=[${n[1]}]"
declare -a n=([0]="zero" [2]="two" [3]="three" [4]="four")
count 4 indices 0 2 3 4
n[1]=[]

The element is gone, but the other elements keep their indexes. The array is now sparse: it has 4 elements, its indexes are 0, 2, 3 and 4, and reading index 1 gives an empty string. Nothing moves down to fill the gap.

Why the Quotes Around n[1]

The quotes in unset 'n[1]' are not decoration. Without them, n[1] is a glob pattern: the brackets form a character class that matches a file named n1. If such a file exists in the current folder, Bash replaces the word with the file name before unset sees it:

m=(a b c)
touch m1
unset m[1]
declare -p m
declare -a m=([0]="a" [1]="b" [2]="c")

The command became unset m1, which removed a variable named m1 (there was none), and the array was left unchanged with no error. In a folder without a matching file, the unquoted form happens to work, which makes the bug depend on where the script runs. Always quote the element name for unset.

Renumbering After Removal

To close the gaps, copy the array onto itself. "${n[@]}" lists only the elements that exist, and the new array is numbered from 0:

n=("${n[@]}")
declare -p n
declare -a n=([0]="zero" [1]="two" [2]="three" [3]="four")

Renumbering is useful before code that walks the array with a counter (lesson 100) or uses the count as an index.

Removing the Last or First Element

A negative index (Bash 4.3 or later) removes the last element, which turns an array into a stack: += pushes and unset 'arr[-1]' pops.

st=(a b c)
top=${st[-1]}
unset 'st[-1]'
echo "$top"; declare -p st
c
declare -a st=([0]="a" [1]="b")

Removing the first element while keeping the array numbered from 0 uses a slice, which turns the array into a queue:

st=(a b c)
first=${st[0]}
st=("${st[@]:1}")
echo "$first"; declare -p st
a
declare -a st=([0]="b" [1]="c")

unset 'st[0]' would also remove the first element, but it would leave the rest at indexes 1 and 2.

An index that does not exist at all is an error for a negative index:

e=(1 2)
unset 'e[-5]'
echo "status $?"
bash: unset: [-5]: bad array subscript
status 1

Removing Elements by Value

unset works by index, so removing every element with a certain value takes a loop. The simplest approach builds a new array of the elements to keep:

fruits=(apple banana cherry banana date)
remove=banana
kept=()
for f in "${fruits[@]}"; do
    [[ $f == "$remove" ]] || kept+=("$f")
done
fruits=("${kept[@]}")
declare -p fruits
declare -a fruits=([0]="apple" [1]="cherry" [2]="date")

Both copies of banana were removed and the result is numbered from 0. The quotes around "$remove" make the comparison literal. Without them, the right side of == is a pattern (lesson 70), so a value such as b* would match more than intended.

If the original indexes must be kept, loop over the indexes and unset the matching ones:

fr=(apple banana cherry banana date)
for i in "${!fr[@]}"; do
    [[ ${fr[i]} == banana ]] && unset 'fr[i]'
done
declare -p fr
declare -a fr=([0]="apple" [2]="cherry" [4]="date")

"${!fr[@]}" lists the indexes before the loop starts, so removing elements while looping is safe here.

Pattern Replacement Does Not Remove Elements

The ${arr[@]/pattern/replacement} expansion (lesson 54) works on every element, which makes it look like a way to remove values. It is not: an element whose whole value is removed becomes an empty string, and it is still there:

x=(apple banana cherry)
y=("${x[@]/banana}")
declare -p y
z=("${x[@]/an/AN}")
declare -p z
declare -a y=([0]="apple" [1]="" [2]="cherry")
declare -a z=([0]="apple" [1]="bANana" [2]="cherry")

The second example also shows that the pattern matches inside values: it changed the first an in banana. For removal by value, use one of the loops above.

Clearing an Array

There are two ways to empty an array, and they leave different results:

c=(1 2 3)
c=()
declare -p c
unset c
declare -p c
declare -a c=()
bash: declare: c: not found

c=() keeps the variable as an empty array, ready for new elements with +=. unset c removes the variable completely, including its array attribute. Prefer c=() when the array will be filled again, for example at the start of each pass through a loop. Inside a function, local -a c=() gives an empty local array (lesson 92).

A Worked Example: A Task Queue

The operations combine naturally. This script keeps a queue of jobs, adds an urgent job at the front, removes a cancelled one, and then processes the queue from the front until it is empty:

#!/usr/bin/env bash
queue=(backup-db rotate-logs send-report)
queue+=(clean-tmp)                 # normal job at the end
queue=(fix-disk "${queue[@]}")     # urgent job at the front

cancel=send-report                 # remove a cancelled job
kept=()
for job in "${queue[@]}"; do
    [[ $job == "$cancel" ]] || kept+=("$job")
done
queue=("${kept[@]}")

while (( ${#queue[@]} > 0 )); do
    job=${queue[0]}
    queue=("${queue[@]:1}")
    echo "running $job (${#queue[@]} left)"
done
running fix-disk (3 left)
running backup-db (2 left)
running rotate-logs (1 left)
running clean-tmp (0 left)

After the urgent job was added and the cancelled one removed, the queue held four jobs: fix-disk, backup-db, rotate-logs and clean-tmp. Each pass of the while loop takes element 0, rebuilds the array from position 1 onward, and then prints how many jobs remain, so the count reaches 0 with the last job. ${#queue[@]} is the number of elements (lesson 101), and because the array is rebuilt each time, the queue always starts at index 0.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Adding and Removing Array Elements and get answers drawn from it.

Signed-in readers only.