From 5fb830eb38276cdca08c7931bc83de426896eaa5 Mon Sep 17 00:00:00 2001 From: koalaman Date: Sun, 10 Nov 2013 11:49:09 -0800 Subject: [PATCH] Created Sc2045 (markdown) --- Sc2045.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Sc2045.md diff --git a/Sc2045.md b/Sc2045.md new file mode 100644 index 0000000..6227d45 --- /dev/null +++ b/Sc2045.md @@ -0,0 +1,25 @@ +# Iterate over globs whenever possible (e.g. 'for f in */*.wav'), as for loops over ls will fail for filenames like 'my file*.txt'. + +### Problematic code: + + for f in $(ls *.wav) + do + echo "$f" + done + +### Correct code: + + for f in *.wav + do + echo "$f" + done + +### Rationale: + +When looping over a set of files, it's always better to use globs when possible. Using command expansion causes word splitting and glob expansion, which will cause problems for certain filenames (typically first seen when trying to process a file with spaces in the name). + +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' \ No newline at end of file