From cbffeb3653df3361082375f554761ddaa4845e0e Mon Sep 17 00:00:00 2001 From: Vidar Holen Date: Fri, 28 Dec 2018 19:36:19 -0800 Subject: [PATCH] Created SC2243 (markdown) --- SC2243.md | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 SC2243.md diff --git a/SC2243.md b/SC2243.md new file mode 100644 index 0000000..175a843 --- /dev/null +++ b/SC2243.md @@ -0,0 +1,44 @@ +## Prefer explicit -n to check for output (or run command without [/[[ to check for success) + +### Problematic code: + +```sh +if [ "$(mycommand --myflags)" ] +then + echo "True" +fi +``` + +### Correct code: + +```sh +# Check that the command outputs something on stdout +if [ -n "$(mycommand --myflags)" ] +then + echo "The command had output on stdout" +fi + +# Check instead that the command succeeded (exit code = 0) +if mycommand --myflags +then + echo "The command reported success" +fi +``` + +(if the command instead outputs "0" or "false", see [[SC2244]] for integer and "boolean" comparisons) + +### Rationale: + +`[ "$(mycommand)" ]` is equivalent to `[ -n "$(mycommand)" ]` and checks whether the command's output on stdout was non-empty. + +Users more familiar with other languages are often surprised to learn that it is nothing like e.g. `if (myfunction())`, since it does not care about what the command/function `return`s. + +Using an explicit `-n` helps clarify that this is purely a string operation. And of course, if the intention was to check whether the command ran successfully, now would be a good time to fix it as in the alternate example. + +### Exceptions: + +If you are familiar with the semantics of `[`, you can [[ignore]] this suggestion with no ill effects. + +### Related resources: + +* Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc! \ No newline at end of file