2

I'd like to do something with each file of some type in a particular directory. I've written, in a bash script,

HANDIN_FILES=`find . -type f -printf "%f\n" | head -20 `
for i in $HANDIN_FILES
do
  echo $i
done

as a kind of first version. This works great if there are no blanks in any filename. If there is a file silly name.txt, then i ends up being first silly and then name.txt, which is not what I want at all.

I know that I could put all the do ... done stuff in a -exec option in the find command, but I'd like to preserve the list of files in a shell variable for later use as well. Can someone suggest a quick fix that'll cause i to have the value silly name.txt on one iteration through the loop?

4

With bash 4.4+:

readarray -td '' files < <(find . -type f -print0 | head -zn 20)
for i in "${files[@]}"; do
  something with "$i"
done

With earlier bash versions:

files=()
while IFS= read -rd '' file; do
  files+=("$file")
done < <(find . -print0 | head -zn 20)

for i...

Here, it's simpler to use zsh:

files=(**/*(D.[1,20]))
for i ($files) something with $i

(at least the file list will be sorted so the first 20 makes more sense)

See Why is looping over find's output bad practice? for other ways to process (or not) find's output.

  • Thanks; that not only solved my problem, but reading the linked stuff provided a bit of education as well! – John Oct 3 '17 at 21:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.