CompTIA Linux+ (XK0-006)Automation, Orchestration and ScriptingEasy

A system administrator is writing a Bash script to process a list of user IDs. The script needs to iterate through each ID, perform a specific operation, and then report the outcome. Which of the following Bash constructs is most appropriate for iterating over a space-separated string of user IDs?

  1. Auntil [ -z "$USER_IDS" ]; do ... done
  2. Bselect id in $USER_IDS; do ... done
  3. Cfor id in $USER_IDS; do ... done
  4. Dwhile read id; do ... done < "$USER_IDS"
Show answer & explanation

Correct answer: C. for id in $USER_IDS; do ... done

The 'for...in' loop is the most direct and idiomatic way in Bash to iterate over a list of items provided as a space-separated string. It automatically splits the string into individual elements.

Why the other options are wrong

  • A. The 'until' loop continues as long as a condition is false; it's not designed for iterating through elements of a string.
  • B. The 'select' construct is used for creating interactive menus, not for non-interactive iteration over a string.
  • D. This construct is typically used for reading line-by-line from a file or here-string, not directly for a space-separated string variable.

Bash 'for...in' loop

A Bash construct used to iterate over a list of items, executing a block of commands for each item in the list.

  • Syntax: `for VAR in LIST; do COMMANDS; done`
  • LIST is typically a space-separated string or an array.
  • Commonly used for processing files, arguments, or elements of a string.

Memory trick: For every item in the list, do the task.

More Automation, Orchestration and Scripting questions