Array Operations and Manipulation

Demonstrates indexed arrays in Bash including declaration, iteration, slicing, appending, sorting, and filtering with practical data processing examples.

BashCli Tooling

Code

snippet
#!/usr/bin/env bash
set -euo pipefail

# Declare and initialize arrays
fruits=("apple" "banana" "cherry")
declare -a numbers=([0]=10 [1]=20 [5]=50)

# Access elements
echo "First: ${fruits[0]}"
echo "All: ${fruits[@]}"
echo "Count: ${#fruits[@]}"

# Append elements
fruits+=("date" "elderberry")
echo "After append: ${fruits[@]}"

# Slice arrays
echo "Slice 1-3: ${fruits[@]:1:3}"
echo "From index 2: ${fruits[@]:2}"

# Iterate with index
for i in "${!fruits[@]}"; do
    echo "  [$i] = ${fruits[$i]}"
done

# Remove element
unset 'fruits[1]'
fruits=("${fruits[@]}")
echo "After removal: ${fruits[@]}"

# Sort array
sorted=($(printf "%s\n" "${fruits[@]}" | sort))
echo "Sorted: ${sorted[@]}"

# Filter array
filtered=()
for fruit in "${fruits[@]}"; do
    [[ ${#fruit} -gt 5 ]] && filtered+=("$fruit")
done
echo "Filtered (>5 chars): ${filtered[@]}"

# Unique elements
all=(1 2 3 2 1 4 5 3)
unique=($(printf "%s\n" "${all[@]}" | sort -u))
echo "Unique: ${unique[@]}"

The moves the code makes

The shebang line is backed by set -euo pipefail: first failure stops the run, unset variables are errors, and a pipeline fails if any stage fails.

The work is delegated to declare and unset, chained through 2 pipes so each stage’s output feeds the next.

Core lines

for i in "${!fruits[@]}"; do
    echo "  [$i] = ${fruits[$i]}"
for fruit in "${fruits[@]}"; do
    [[ ${#fruit} -gt 5 ]] && filtered+=("$fruit")

Interactive Tools for This Topic

FAQ

Does the script stop on the first error?
Yes — `set -euo pipefail` aborts on the first failing command, treats unset variables as errors, and fails the whole pipeline if any stage fails. Nothing continues half-broken.
Which external commands does the script rely on?
`declare`, `unset` must be available on the PATH environment variable; everything else is shell built-in syntax.