Array Operations and Manipulation
Demonstrates indexed arrays in Bash including declaration, iteration, slicing, appending, sorting, and filtering with practical data processing examples.
Code
#!/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
Bitwise Operations CalculatorCompute AND, OR, XOR, NOT, and shifts on 32-bit unsigned operands with binary, hex, and signed decimal views.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.