for
-loops are usually done over static data. That is, data that will not change over the course of the loop, or over a known interval.
while
-loops are usually used when it is not known how many iterations will be needed, like prompting a user for input and validating the response until it's correct, or looping over the data read from file or a pipe.
In this case, you are looping over filenames read directly from the current directory, given to the loop by the shell expanding a file globbing pattern. A for
loop is the correct looping construct to use. A while
loop would only complicate matters and make the code harder to read and to get right.
This would be one example of a while
loop doing the same thing as your for
loop:
printf '%s\n' DSC*.JPEG | while read -r name; do [ ! -f "Paris${name#DSC}" ] && mv "$name" "Paris${name#DSC}" done
There are issues here:
- The filenames can't contain newlines since the loop reads newline-separated names. We could get around this by getting
printf
to output \0
-separated filenames and read
to read these, but that would make it even more complicated (and non-portable). - There is no gain whatsoever. The list of names is still static and we've introduced a redundant step to pass these names from
printf
to the loop, a step that brought issues with what characters we can allow the filenames to contain (see previous point).
Really, the only thing wrong with your code is that the variable expansions are unquoted.
while
loop.