Processing

What

Process each element of the array CODE_EXTENSIONS_ARRAY separately in a pipeline (pipe)

Wrapper way

CODE_EXTENSIONS_ARRAY=(
  "kt" "kts" "java" "js" "ts"
  "html" "css" "scss" "xml"
  "yml" "yaml" "sh" "py"
)

arrays.print_elements() {
  local -n array_ref="$1"  # Use a nameref to refer to the input array
  printf '%s\n' "${array_ref[@]}"
}

main() {
  arrays.print_elements CODE_EXTENSIONS_ARRAY | while IFS= read -r element; do
    echo "Processing: $element"
  done
}

main "${@}" || exit 1

Raw

Example: Processing Each Array Element in a Pipeline

# Export the array
export CODE_EXTENSIONS_ARRAY=()
CODE_EXTENSIONS_ARRAY+=("kt")
CODE_EXTENSIONS_ARRAY+=("kts")
CODE_EXTENSIONS_ARRAY+=("java")
CODE_EXTENSIONS_ARRAY+=("js")
CODE_EXTENSIONS_ARRAY+=("ts")
CODE_EXTENSIONS_ARRAY+=("html")
CODE_EXTENSIONS_ARRAY+=("css")
CODE_EXTENSIONS_ARRAY+=("scss")
CODE_EXTENSIONS_ARRAY+=("xml")
CODE_EXTENSIONS_ARRAY+=("yml")
CODE_EXTENSIONS_ARRAY+=("yaml")
CODE_EXTENSIONS_ARRAY+=("sh")
CODE_EXTENSIONS_ARRAY+=("py")

# Process each element in the array
printf '%s\n' "${CODE_EXTENSIONS_ARRAY[@]}" | while IFS= read -r extension; do
  # Process each extension (replace `echo` with your processing command)
  echo "Processing: $extension"
done

Explanation:

  1. printf '%s\n' "${CODE_EXTENSIONS_ARRAY[@]}":

    • Outputs each element of the array on a separate line.
  2. | while IFS= read -r extension; do:

    • Pipes the output of printf to a while loop, where each line is read into the variable extension.
  3. Processing Logic:

    • Replace echo "Processing: $extension" with the actual command or logic to process each element.

Advanced Example: Combining with a Command

If you want to pass each array element as an argument to a command, you can use xargs:

printf '%s\n' "${CODE_EXTENSIONS_ARRAY[@]}" | xargs -I {} echo "Processing file extension: {}"

Output:

Processing file extension: kt
Processing file extension: kts
Processing file extension: java
...
Processing file extension: py

Alternative with a Loop:

If you don't need a true pipeline but want to process each element programmatically, you can use a for loop:

for extension in "${CODE_EXTENSIONS_ARRAY[@]}"; do
  # Replace this with your processing logic
  echo "Processing: $extension"
done

This approach avoids the need for printf and pipes but doesn't integrate as cleanly into pipelines.


Let me know how you plan to process the extensions, and I can help refine the solution!


Backlinks