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

  1. Definition:

    • In shell (particularly Bash), arrays are zero-indexed collections of elements that can be accessed using indices.
    • Bash supports one-dimensional arrays.
  2. 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)
      
  3. Accessing Array Elements:

    • Individual elements can be accessed using their index.
    • Example:
      echo ${array[0]}  # Outputs: item1
      
  4. Modifying Arrays:

    • You can update elements by specifying their index.
    • Example:
      array[1]="newItem"  # Changes item2 to newItem
      
  5. 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
      
  6. Associative Arrays (Bash 4+):

    • Associative arrays use strings as keys.
    • Declaring associative arrays:
      declare -A assocArray
      assocArray[key1]="value1"
      assocArray[key2]="value2"
      
  7. Accessing Associative Array Elements:

    • Example:
      echo ${assocArray[key1]}  # Outputs: value1
      

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.

  1. Creating Lists:

    • Lists are typically created by space-separated values or by using commands like seq.
    • Example:
      list="item1 item2 item3"
      
  2. Accessing and Iterating over Lists:

    • Use loops to iterate:
      for item in $list; do
          echo $item
      done
      
  3. 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
      
  4. Handling Lists with Commands:

    • To handle multi-line output, use commands like mapfile (or readarray in Bash).
    • Example:
      mapfile -t lines < <(command)
      for line in "${lines[@]}"; do
          echo $line
      done
      

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.