Linux Basic — Manipulating Arrays

1 minute read

Manipulating Arrays

Bash has two array types: indexed (numeric keys) and associative (string keys). They’re more powerful than most scripters realise — and they’re the cleanest way to handle lists of filenames, sets of unique values, key/value lookup tables, and ordered command arguments.

This chapter is the full tour.


What You Will Learn

By the end of this chapter you will be able to:

  • Create, read, update, and delete entries in indexed arrays
  • Use associative arrays (Bash 4+) as in-memory hash maps
  • Slice arrays and make safe copies
  • Sort arrays alphabetically or numerically (Bash + sort)
  • Know exactly when to use an array vs a string and avoid the classic for x in $list bug

Topics in This Chapter

# Topic Description
1 Indexed Array CRUD declare, append, read, delete
2 Associative Array CRUD declare -A, key/value, iterate
3 Array Slicing & Copying ${arr[@]:1:3}, deep copy
4 Sorting Arrays native + sort integration
5 Array vs String why "$@" ≠ $*; quoting rules
6 Practice Exercises Hands-on tasks

Quick Mental Model

# Indexed — integer keys, ordered
fruits=(apple banana cherry)
echo "${fruits[0]}"        # apple

# Associative — string keys, unordered (Bash 4+)
declare -A user
user[name]=alice
user[role]=admin
echo "${user[name]}"       # alice

Two rules to memorise:

  1. ${arr[@]} with the "@" and quotes is the safe way to expand all elements — each as its own word.
  2. ${arr[*]} joins all elements with the first char of IFS. Useful for printing, dangerous for iterating.

We’ll go deep on this in the Array vs String page.


Next → Indexed Array CRUD

Updated: