Practical examples of working with arrays in shell scripting: 3 examples you’ll actually use
Before anything fancy, you need a clean, readable pattern for iterating over a list. This is the baseline example of working with arrays in shell scripting that everything else builds on.
#!/usr/bin/env bash
## Bash indexed array of filenames
files=("report.csv" "data.csv" "summary.txt")
for file in "${files[@]}"; do
if [[ -f "$file" ]]; then
echo "Found: $file"
else
echo "Missing: $file"
fi
done
echo "Total files in array: ${#files[@]}"
Key points buried in this tiny script:
files=(...)creates an indexed array."${files[@]}"expands to each element as a separate word, preserving spaces.${#files[@]}gives you the array length.
This is one of the best examples of working with arrays in shell scripting because it mirrors a very common, very boring, but very real task: checking a list of expected files. Once you’re comfortable with this pattern, you can start layering in more logic.
2. Filtering and transforming data: examples of working with arrays in shell scripting in real workflows
Real scripts don’t just list values; they filter, transform, and classify them. The next set of examples of working with arrays in shell scripting: 3 examples focuses on turning raw data into something structured.
Example 2A: Split a PATH-like string into an array
You’ll see this pattern in installers, environment setup scripts, and CI jobs.
#!/usr/bin/env bash
IFS=':' read -r -a path_parts <<< "$PATH"
echo "You have ${#path_parts[@]} PATH entries"
for dir in "${path_parts[@]}"; do
[[ -d "\(dir" ]] && echo "Dir exists: \)dir" || echo "Broken entry: $dir"
done
This example of working with arrays in shell scripting shows how to:
- Use
IFSandread -ato split a string into an array. - Validate each entry in a configuration-like string.
It’s the same pattern you’d use to process a colon- or comma-separated list from a config file or environment variable.
Example 2B: Filter log files by size
Modern systems generate ridiculous amounts of logs. Here’s one of the more practical real examples of array usage: find large log files and report them.
#!/usr/bin/env bash
## Collect log files into an array
mapfile -t logs < <(find /var/log -type f -name '*.log' 2>/dev/null)
large_logs=()
for log in "${logs[@]}"; do
size_kb=\((du -k "\)log" | awk '{print $1}')
if (( size_kb > 10240 )); then # > 10 MB
large_logs+=("$log")
fi
done
if (( ${#large_logs[@]} )); then
echo "Log files over 10 MB:"
printf ' %s\n' "${large_logs[@]}"
else
echo "No log files over 10 MB found."
fi
Here you see another of the best examples of working with arrays in shell scripting:
mapfile -treads command output directly into an array.- A second array,
large_logs, stores only the items that match your criteria.
This pattern maps nicely to modern observability and maintenance workflows where you’re constantly scanning for outliers.
For broader background on shell environments and scripting in Unix-like systems, the GNU Bash reference manual is still the gold standard.
3. Associative arrays: examples include key-value style configuration
Bash 4+ introduced associative arrays, and they’re wildly underused. These are perfect when you want to map keys to values instead of juggling parallel arrays.
Example 3A: HTTP status code descriptions
This is a compact example of working with associative arrays in shell scripting.
#!/usr/bin/env bash
## Requires Bash 4+
declare -A http_status
http_status=([
200]="OK" \
[404]="Not Found" \
[500]="Internal Server Error"
)
codes=(200 404 500 418)
for code in "${codes[@]}"; do
if [[ -n "\({http_status[\)code]}" ]]; then
echo "\(code: }\(http_status[$code]}"
else
echo "$code: Unknown status"
fi
done
This is one of those examples of working with arrays in shell scripting: 3 examples where the associative variant saves you from case statements and fragile if chains.
Example 3B: Simple configuration map
Think of a tiny, script-level configuration system:
#!/usr/bin/env bash
declare -A config
config=(
[env]="production"
[region]="us-east-1"
[max_retries]="5"
)
## Use the config values
if [[ "${config[env]}" == "production" ]]; then
echo "Running in production in region ${config[region]}"
fi
echo "Max retries: ${config[max_retries]}"
This kind of pattern shows up in deployment scripts and CI jobs all the time. It’s another of the best examples of working with arrays in shell scripting because it trades hard-coded literals for a single, readable map you can tweak in one place.
For a deeper look at shell scripting patterns used in modern systems administration, the free materials from MIT’s missing semester (MIT CSAIL, .edu) are worth a read.
4. DevOps-style examples of working with arrays in shell scripting
So far we’ve hit the headline examples of working with arrays in shell scripting: 3 examples, but real life rarely stops at three. Let’s walk through a few more workflows that show how these patterns play out in 2024–2025 DevOps environments.
Example: Bulk user checks with an array
User and group audits are still a thing, especially on shared Linux servers and in regulated environments.
#!/usr/bin/env bash
users=("alice" "bob" "carol")
for user in "${users[@]}"; do
if id "$user" &>/dev/null; then
echo "User exists: $user"
else
echo "User missing: $user"
fi
done
This simple example of working with arrays in shell scripting is the core of many compliance and security checks, often wrapped by larger tools.
Example: Parallel command arguments
Containers, microservices, and cloud CLIs all encourage command-heavy workflows. Arrays keep argument lists sane.
#!/usr/bin/env bash
base_cmd=(aws ec2 describe-instances)
filters=(
"Name=instance-state-name,Values=running"
"Name=tag:Environment,Values=prod"
)
aws_output=("\({base_cmd[@]}" --filters "}\(filters[@]}")
"${aws_output[@]}"
This is one of the more subtle real examples of array usage: building a command as an array so you don’t lose quoting and spacing when you add options dynamically.
The same pattern shows up in scripts that wrap tools like kubectl, docker, or podman.
Example: Safe file deletion with review step
Instead of immediately deleting files, build a list in an array, review it, then act.
#!/usr/bin/env bash
mapfile -t old_logs < <(find /var/log -type f -mtime +30 -name '*.log' 2>/dev/null)
echo "Found ${#old_logs[@]} candidate log files for deletion."
printf ' %s\n' "${old_logs[@]}"
echo -n "Delete these files? [y/N] "
read -r answer
if [[ "$answer" == [yY] ]]; then
rm -f -- "${old_logs[@]}"
echo "Deleted ${#old_logs[@]} files."
else
echo "Aborted. No files deleted."
fi
This is a very practical example of working with arrays in shell scripting: you store a set of potentially destructive targets in an array, show them to the user, and only then execute.
5. Performance and portability notes for 2024–2025
Shell scripting hasn’t exactly changed at the pace of JavaScript frameworks, but the context around it has:
- Bash 4+ is now standard on most modern Linux distributions, which means associative arrays are safe to rely on in many server environments. On macOS, Bash 3 is still the system default, but newer Bash can be installed via Homebrew.
- Containers and CI pipelines favor small, repeatable scripts. Arrays make it much easier to keep those scripts readable as they grow.
- Security guidance from organizations like NIST continues to recommend minimizing ad-hoc, copy-paste shell commands in favor of repeatable scripts. Arrays help structure those scripts so they’re auditable and less error-prone. You can browse general secure scripting guidelines in the NIST Secure Software Development Framework (NIST,
.gov).
When you look at the best examples of working with arrays in shell scripting, a pattern emerges: they’re not fancy, they’re just structured. Arrays are how you keep your script from turning into a pile of copy-pasted if blocks and half-broken loops.
FAQ: Short answers and more examples
What are some common examples of working with arrays in shell scripting?
Common examples include:
- Storing a list of files to process (backups, logs, reports).
- Keeping a list of users, hosts, or services to check.
- Building complex command arguments safely.
- Splitting configuration strings (like
PATH) into arrays. - Using associative arrays to map codes (like HTTP status or exit codes) to human-readable messages.
All of these examples of working with arrays in shell scripting show up constantly in real-world automation.
Can I use these array examples in POSIX /bin/sh?
Not directly. Indexed arrays and associative arrays are Bash features, not POSIX shell features. If you need strict POSIX compatibility, you’ll have to emulate arrays with positional parameters or by iterating over strings. For most modern Linux scripting, Bash is available and preferred, so the examples of working with arrays in shell scripting shown here assume Bash.
What’s a simple example of using an array for error handling?
You can collect failing items into an array for a summary at the end:
failed=()
for host in "${hosts[@]}"; do
if ! ping -c1 -W1 "$host" &>/dev/null; then
failed+=("$host")
fi
done
if (( ${#failed[@]} )); then
echo "Unreachable hosts: ${failed[*]}"
fi
This example of error aggregation keeps your main loop clean and gives you a clear summary after the fact.
Where can I learn more about shell scripting best practices?
A few solid resources:
- The GNU Bash manual for authoritative syntax and behavior.
- MIT’s Missing Semester: Shell Tools & Scripting for modern, practical usage.
- NIST’s software security publications for high-level guidance on writing safer automation.
Use these alongside the real examples in this article, and you’ll quickly get comfortable adapting arrays to your own scripts.
Related Topics
Practical examples of examples of variables in shell scripting
Examples of Regular Expressions in Shell Scripts: 3 Practical Examples You’ll Actually Use
Practical examples of command-line arguments in shell scripts examples
Practical examples of shell script examples for beginners
Practical examples of working with arrays in shell scripting: 3 examples you’ll actually use
Practical examples of string manipulation in shell scripts: 3 examples that actually matter
Explore More Shell Scripting Snippets
Discover more examples and insights in this category.
View All Shell Scripting Snippets