Looping over filenames with spaces

Back to list2024-02-09
You

My loop breaks on filenames containing spaces.

ChatGPT

Word splitting is doing exactly what it was told. Use null separators end to end:

find . -name '*.json' -print0 |
  while IFS= read -r -d '' file; do
    printf '%s\n' "$file"
  done

The quotes around "$file" matter as much as the null delimiter; either one alone still breaks.

You

How do I retry a network command a few times in bash?

ChatGPT

A small loop with backoff beats reaching for a tool:

for attempt in 1 2 3 4 5; do
  if curl -fsS "$url" -o "$out"; then break; fi
  sleep $(( attempt * 2 ))
done

The -f is essential: without it curl exits zero on a 500 and writes the error page into your output file.

You

How do I know when it stops being worth it?

ChatGPT

When you stop noticing it. If it has not surfaced a problem in six months, it is either solved or it was never the bottleneck you thought.