On this page
- Why use an array instead of a space separated string?
- How do I create an indexed array and read from it?
- What is the difference between [@] and [*]?
- How do I add, change and remove elements?
- How do associative arrays work?
- How do I fill an array from a file or a command?
- How do I build a command line safely with an array?
- How do I sort, filter or deduplicate an array?
- Questions
Why use an array instead of a space separated string?
An array keeps each item as a separate value, even when items contain spaces, quotes or glob characters. A string like files="a.txt my notes.txt" cannot tell where one name ends, and every expansion of it risks being split or globbed in the wrong place. With an array the boundaries are stored, not guessed.
Bash has two kinds: indexed arrays, numbered from 0, for ordered lists such as servers to visit or files to process, and associative arrays, keyed by strings, for lookups such as service name to port. Both exist in Bash 4 and later, so they work on every Linux image you can deploy (Bash 5.1 or 5.2). They are not available in sh, so scripts using them need #!/usr/bin/env bash as their first line, as set up in Write and run a Bash script.
How do I create an indexed array and read from it?
List the items inside parentheses, separated by spaces, and quote any item that contains spaces:
hosts=(web1.example.net web2.example.net "db 1.example.net")
echo "${hosts[0]}" # first element
echo "${hosts[-1]}" # last element
echo "${#hosts[@]}" # number of elements: 3
echo "${hosts[@]:1:2}" # slice: two elements from index 1
printf '%s\n' "${hosts[@]}"
declare -p hostsThe braces are required: $hosts[0] prints the first element followed by the literal text [0]. Using the array name alone, $hosts, gives only element 0, a frequent source of confusion. declare -p prints the whole array with its indexes, the quickest way to see what a script really stored.
What is the difference between [@] and [*]?
Inside double quotes, "${arr[@]}" expands to one word per element, while "${arr[*]}" joins all elements into a single word, separated by the first character of IFS (a space by default). Use [@] for passing items to commands and loops, and [*] only for joining:
dirs=("/srv/my site" /var/www)
for d in "${dirs[@]}"; do echo "[$d]"; done
# [/srv/my site]
# [/var/www]
( IFS=,; echo "${dirs[*]}" )
# /srv/my site,/var/wwwThe parentheses around the join run it in a subshell, so the changed IFS does not affect the rest of the script. Unquoted, both forms split on spaces and lose the boundaries, which defeats the purpose of using an array.
How do I add, change and remove elements?
Append with +=, assign by index, and delete with unset:
pkgs=(curl git)
pkgs+=(htop "jq")
pkgs[1]="git-core"
unset 'pkgs[0]'
echo "${!pkgs[@]}" # indexes left: 1 2 3
pkgs=("${pkgs[@]}") # renumber from 0
echo "${!pkgs[@]}" # 0 1 2After unset the array has a gap, so loop over "${!pkgs[@]}" (the list of indexes) instead of counting from 0 to the length, or renumber it as shown. Quote the unset argument so a file named pkgs0 in the current folder cannot be matched as a glob. To empty an array completely, assign pkgs=().
How do associative arrays work?
Declare them with declare -A before the first use, then use strings as keys:
declare -A port=(
[ssh]=22
[http]=80
[https]=443
)
port[postgres]=5432
echo "${port[https]}"
for svc in "${!port[@]}"; do
printf '%-9s %s\n' "$svc" "${port[$svc]}"
done
[[ -v port[redis] ]] || echo "no redis entry"
unset 'port[http]'Without declare -A, Bash silently creates an indexed array and every key evaluates to index 0, so all your values overwrite each other. The loop order of keys is not sorted; pipe the output through sort when order matters. The -v test checks whether a key exists, even when its value is empty. Inside a function, local -A creates a local associative array.
How do I fill an array from a file or a command?
mapfile (also called readarray) reads lines into an array, one line per element; -t strips the newline:
mapfile -t users < <(awk -F: '$3 >= 1000 && $3 < 60000 {print $1}' /etc/passwd)
echo "${#users[@]} regular users: ${users[*]}"
mapfile -t -d '' logs < <(find /var/log -name "*.gz" -mtime +30 -print0)
echo "${#logs[@]} old archives"
read -r -a parts <<< "198.51.100.24 22 deploy"
echo "address ${parts[0]}, port ${parts[1]}"The second mapfile uses null separated input, which is safe for any file name. read -a splits a single line into words, good for parsing short records. Avoid arr=($(command)): it splits on every space and expands globs, the very problems arrays are meant to solve.
How do I build a command line safely with an array?
Collect the arguments in an array and expand it quoted. This is the reliable way to add options conditionally without fighting quotes:
#!/usr/bin/env bash
src="/srv/app/"
dest="deploy@198.51.100.24:/srv/app/"
opts=(-a --delete --exclude ".git/")
[[ "${DRY_RUN:-0}" == 1 ]] && opts+=(--dry-run --itemize-changes)
[[ -f .rsyncignore ]] && opts+=(--exclude-from ".rsyncignore")
rsync "${opts[@]}" "$src" "$dest"Each option stays exactly one argument, so an exclude pattern with spaces works. Printing the array with printf '%q ' "${opts[@]}"; echo shows the command in a form you can paste back into a shell, ideal for logging what a script is about to run.
How do I sort, filter or deduplicate an array?
Bash has no built in sort, so pass the elements through sort and read them back with mapfile:
names=(delta alpha charlie alpha bravo)
mapfile -t sorted < <(printf '%s\n' "${names[@]}" | sort -u)
echo "${sorted[@]}" # alpha bravo charlie delta
keep=()
for n in "${names[@]}"; do
[[ $n == a* ]] && keep+=("$n")
done
declare -A seen=()
for n in "${names[@]}"; do seen[$n]=1; done
echo "${!seen[@]}"The associative array trick removes duplicates without sorting. Arrays cannot be exported to child processes and cannot be nested; for real structured data such as JSON, let jq handle it. Passing arrays into functions is covered in Functions in Bash.
Questions about Arrays in Bash
Do Bash arrays start at 0 or 1?
Indexed arrays start at 0. Zsh starts at 1, which is why scripts copied between the two shells sometimes go wrong.
Can an array hold numbers and text together?
Yes. Every element is a string; elements only act as numbers inside arithmetic such as $(( arr[0] + 1 )).
How do I check if an array contains a value?
Loop and compare, or for frequent checks keep an associative array of the values and test [[ -v set[$value] ]], which avoids a loop.
How do I pass an array to another script?
Expand it as arguments: ./other.sh "${list[@]}". The other script receives them as "$@" and can rebuild the array with items=("$@").
Is there a size limit?
Only memory and the kernel limit on argument length when you pass a huge array to an external command. For thousands of file names, stream them to xargs -0 instead.