10 ‐ List & Arrays - CloudScope/DevOpsWithCloudScope GitHub Wiki
In shell scripting, arrays and lists are essential data structures that allow you to store and manipulate collections of items. Here’s a breakdown of their usage and key points:
Arrays in Shell
-
Definition:
- In shell (particularly Bash), arrays are zero-indexed collections of elements that can be accessed using indices.
- Bash supports one-dimensional arrays.
-
Declaring Arrays:
- Arrays can be declared explicitly using parentheses or assigned values using the
declare
command. - Examples:
# Explicit declaration array=(item1 item2 item3) # Using declare command declare -a array=(item1 item2 item3)
- Arrays can be declared explicitly using parentheses or assigned values using the
-
Accessing Array Elements:
- Individual elements can be accessed using their index.
- Example:
echo ${array[0]} # Outputs: item1
-
Modifying Arrays:
- You can update elements by specifying their index.
- Example:
array[1]="newItem" # Changes item2 to newItem
-
Array Operations:
- Length: To get the number of elements in an array:
echo ${#array[@]} # Outputs the length of the array
- All Elements: To access all elements:
echo ${array[@]} # Prints all elements in the array
- Iterating over Arrays:
for item in "${array[@]}"; do echo $item done
- Length: To get the number of elements in an array:
-
Associative Arrays (Bash 4+):
- Associative arrays use strings as keys.
- Declaring associative arrays:
declare -A assocArray assocArray[key1]="value1" assocArray[key2]="value2"
-
Accessing Associative Array Elements:
- Example:
echo ${assocArray[key1]} # Outputs: value1
- Example:
Lists in Shell
In shell scripting, lists are often just space-separated strings or newline-separated items that can be processed with commands like for
, while
, or tools like read
and xargs
.
-
Creating Lists:
- Lists are typically created by space-separated values or by using commands like
seq
. - Example:
list="item1 item2 item3"
- Lists are typically created by space-separated values or by using commands like
-
Accessing and Iterating over Lists:
- Use loops to iterate:
for item in $list; do echo $item done
- Use loops to iterate:
-
Converting Strings to Arrays:
- You can convert a list (string) to an array by splitting on whitespace.
- Example:
array=($list) echo ${array[0]} # Outputs: item1
-
Handling Lists with Commands:
- To handle multi-line output, use commands like
mapfile
(orreadarray
in Bash). - Example:
mapfile -t lines < <(command) for line in "${lines[@]}"; do echo $line done
- To handle multi-line output, use commands like
Key Points
- Arrays provide indexed access and are more structured compared to simple lists.
- Associative arrays allow mapping of keys to values and are available in newer versions of Bash.
- Lists are more flexible for iteration and are commonly used in shell scripts for handling command outputs.