Fix the dry run for a backup cleanup loop

Review the AI's codeEasy10 min

Your task

A deploy script deletes old backups with for f in $(ls /var/backups). An AI explanation called the loop safe because it "iterates over every file". Before the script runs on a production server, your team dry runs it to see every value the loop variable f takes. The shell splits the output of $(ls ...) into words, so a file name can turn into more than one value.

An assistant wrote unsafe_loop_targets(filenames). It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • filenames: the file names ls prints, in order. A name can hold any character, including spaces, tabs and newlines.
  • Return the list of values f takes, in order.

Rules the tests check:

  • Split each name into words. A space, a tab, a newline or a carriage return separates words.
  • A run of separators is one break. Separators at the start or end of a name make no empty words.
  • An empty name, or a name made only of separators, gives no words.
  • The words of one name come before the words of the next name.
  • Every other character stays as it is, including a leading -.

Examples

unsafe_loop_targets(filenames: list[str]) -> list[str]
Example 1
Inputunsafe_loop_targets(["jan 2026.tar", "app.log"])
Output["jan", "2026.tar", "app.log"]
Example 2
Inputunsafe_loop_targets(["backup.tar", "db.sql"])
Output["backup.tar", "db.sql"]