From 490baffcaa9c3b032be98d69ef61b78bbbe26f96 Mon Sep 17 00:00:00 2001 From: koalaman Date: Sat, 1 Oct 2016 14:18:46 -0700 Subject: [PATCH] Created SC1014 (markdown) --- SC1014.md | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 SC1014.md diff --git a/SC1014.md b/SC1014.md new file mode 100644 index 0000000..5463363 --- /dev/null +++ b/SC1014.md @@ -0,0 +1,43 @@ +## Use 'if cmd; then ..' to check exit code, or 'if [\[ $(cmd) == .. ]]' to check output. + +### Problematic code: + +```sh +if [ grep -q pattern file ] +then + echo "Found a match" +fi +``` + +### Correct code: + +```sh +if grep -q pattern file +then + echo "Found a match" +fi + +``` +### Rationale: + +`[ .. ]` is not part of shell syntax like `if` statements. It is not equivalent to parentheses in C-like languages, `if (foo) { bar; }`, and should not be wrapped around commands to test. + +`[` is just regular command, like `whoami` or `grep`, but with a funny name (see `ls -l /bin/[`). It's a shorthand for `test`. + +If you want to check the exit status of a certain command, use that command directly as demonstrated in the correct code. + +If you want to check the output of a command, use `"$(..)"` to get its output, and then use `test` or `[`/`[[` to do a string comparison: + +``` +# Check output of `whoami` against the string `root` +if [ "$(whoami)" = "root" ] +then + echo "Running as root" +fi +``` + +For more information, see [this problem in the Bash Pitfall](http://mywiki.wooledge.org/BashPitfalls#if_.5Bgrep_foo_myfile.5D) list, or generally [Test and Conditionals](http://mywiki.wooledge.org/BashGuide/TestsAndConditionals) in the WoolEdge BashGuide + +### Exceptions: + +None. \ No newline at end of file