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

A system administrator is writing a Bash script to iterate through a list of usernames stored in a file named `users.txt`, one username per line. For each username, the script needs to perform a specific action. Which of the following Bash constructs is most appropriate for reading each line from `users.txt` and processing it?

  1. Awhile IFS= read -r user; do ... done < users.txt
  2. Bfor user in $(cat users.txt); do ... done
  3. Cls -1 users.txt | while read user; do ... done
  4. Dcat users.txt | xargs -I {} bash -c 'user={}; ...'
Show answer & explanation

Correct answer: A. while IFS= read -r user; do ... done < users.txt

The `while IFS= read -r user; do ... done < users.txt` construct is the most robust and idiomatic way to read a file line by line in Bash, correctly handling spaces, backslashes, and other special characters within filenames.

Why the other options are wrong

  • B. This approach is prone to word splitting and globbing issues if usernames contain spaces or special characters, as `cat` output is expanded by the shell.
  • C. `ls -1 users.txt` would only output the filename `users.txt`, not its contents line by line, making this incorrect for the stated goal.
  • D. `xargs` can be used, but it's more complex for simple line-by-line processing within a script and might introduce subshell issues if not carefully managed; `while read` is simpler and more direct.

Bash `while IFS= read -r` Loop

A Bash construct used to reliably read a file line by line, preserving whitespace and handling special characters correctly.

  • `IFS=` prevents word splitting on whitespace.
  • `-r` option to `read` prevents backslash interpretation.
  • Redirects file content as input to the `while` loop.

Memory trick: Read files carefully, line by line, to avoid splitting woes.

More Automation, Orchestration and Scripting questions