diff --git a/SC2045.md b/SC2045.md index 8f2a557..aafb233 100644 --- a/SC2045.md +++ b/SC2045.md @@ -2,18 +2,22 @@ ### Problematic code: - for f in $(ls *.wav) - do - echo "$f" - done +```sh +for f in $(ls *.wav) +do + echo "$f" +done +``` ### Correct code: - for f in *.wav - do - [[ -e "$f" ]] || break # handle the case of no *.wav files - echo "$f" - done +```sh +for f in *.wav +do + [[ -e "$f" ]] || break # handle the case of no *.wav files + echo "$f" +done +``` Also note that in Bash, `shopt -s nullglob` will allow the loop to run 0 times instead of 1 if there are no matches. There are also [several other conditions](http://mywiki.wooledge.org/BashPitfalls#for_i_in_.24.28ls_.2A.mp3.29) to be aware of. @@ -23,10 +27,12 @@ When looping over a set of files, it's always better to use globs when possible. The following files can or will break the first loop: - touch 'filename with spaces.wav' - touch 'filename with * globs.wav' - touch 'More_Globs[2003].wav' - touch 'files_with_fønny_chæracters_in_certain_locales.wav' +```sh +touch 'filename with spaces.wav' +touch 'filename with * globs.wav' +touch 'More_Globs[2003].wav' +touch 'files_with_fønny_chæracters_in_certain_locales.wav' +``` ### Related resources: