Bash arrays: syntax reference
Create, read, modify and loop over indexed arrays in Bash, with a reference of the common syntax.
Bash supports indexed arrays. The table below lists the common syntax to create, read, modify and loop over them.
Syntax reference
| Syntax | Result |
|---|---|
arr=() |
Create an empty array |
arr=(1 2 3) |
Initialise an array |
${arr[2]} |
Retrieve the third element |
${arr[@]} |
Retrieve all elements |
${!arr[@]} |
Retrieve the array indices |
${#arr[@]} |
Count the elements |
arr[0]=3 |
Overwrite the first element |
arr+=(4) |
Append one or more values |
str=$(ls) |
Store the output of ls in a string |
arr=( $(ls) ) |
Store the output of ls in an array, split on whitespace |
${arr[@]:s:n} |
Retrieve n elements starting at offset s |
Looping over the elements
allThreads=(1 2 4 8 16 32 64 128)
for t in ${allThreads[@]}; do
./pipeline --threads $t
done
Looping over the indices
for i in ${!allThreads[@]}; do
./pipeline --threads ${allThreads[$i]}
done
Notes
arr=( $(ls) )splits the output on whitespace, so file names that contain spaces are split into several elements. Use a glob instead (files=( * )) for file names.- The loops above leave
${allThreads[@]}unquoted, as in the original example. Write"${allThreads[@]}"if the elements can contain spaces.