From 98c0dbb74a4c17fce7ec773e9104dc7645451229 Mon Sep 17 00:00:00 2001 From: koalaman Date: Sun, 25 May 2014 12:03:06 -0700 Subject: [PATCH] Created SC2144 (markdown) --- SC2144.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 SC2144.md diff --git a/SC2144.md b/SC2144.md new file mode 100644 index 0000000..de8bd36 --- /dev/null +++ b/SC2144.md @@ -0,0 +1,31 @@ +## -e doesn't work with globs. Use a for loop. + +### Problematic code: + + if [ -e dir/*.mp3 ] + then + echo "There are mp3 files." + fi + +### Correct code: + + for file in dir/*.mp3 + do + if [ -e "$file" ] + then + echo "There are mp3 files" + break + fi + done + +### Rationale: + +`[ -e file* ]` only works if there's 0 or 1 matches. If there are multiple, it becomes `[ -e file1 file2 ]`, and the test fails. + +`[[ -e file* ]]` doesn't work at all. + +Instead, use a for loop to expand the glob and check each result individually. + +### Contraindications + +None. \ No newline at end of file