From 95a8cf93c90b5b8a215cd20c4d79ea1032b86acc Mon Sep 17 00:00:00 2001 From: Ng Zhi An Date: Sat, 22 Dec 2018 21:59:38 +0800 Subject: [PATCH] Add check for ambiguous nullary test Given an input like `if [[ $(a) ]]; then ...`, this is a implicit `-n` test, so it works like `if [[ -n $(a) ]]; then ...`. Users might confuse this for a check for the exit code of the command a, which should be tested with: if a; then ... We warn the user to be more explicity and specifity the `-n`. Fixes #1416 --- src/ShellCheck/Analytics.hs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/ShellCheck/Analytics.hs b/src/ShellCheck/Analytics.hs index 9b407f8..5b8d1bd 100644 --- a/src/ShellCheck/Analytics.hs +++ b/src/ShellCheck/Analytics.hs @@ -170,6 +170,7 @@ nodeChecks = [ ,checkSubshelledTests ,checkInvertedStringTest ,checkRedirectionToCommand + ,checkNullaryExpansionTest ] @@ -3096,5 +3097,21 @@ checkRedirectionToCommand _ t = warn id 2238 "Redirecting to/from command name instead of file. Did you want pipes/xargs (or quote to ignore)?" _ -> return () +prop_checkNullaryExpansionTest1 = verify checkNullaryExpansionTest "[[ $(a) ]]" +prop_checkNullaryExpansionTest2 = verify checkNullaryExpansionTest "[[ $a ]]" +prop_checkNullaryExpansionTest3 = verifyNot checkNullaryExpansionTest "[[ $a=1 ]]" +prop_checkNullaryExpansionTest4 = verifyNot checkNullaryExpansionTest "[[ -n $(a) ]]" +checkNullaryExpansionTest _ t = + case t of + TC_Nullary _ _ (T_NormalWord id [T_DollarExpansion _ [T_Pipeline _ [] [x]]]) -> + when (isJust (getCommand x)) $ + style id 2243 ( + "To check for the exit code of a command, remove the conditional expression, e.g. if foo; ...") + TC_Nullary _ _ (T_NormalWord id [t2]) -> + when ((not . isConstant) t2) $ + style id 2244 ( + "Use -n to check for null string, e.g. [[ -n $var ]].") + _ -> return () + return [] runTests = $( [| $(forAllProperties) (quickCheckWithResult (stdArgs { maxSuccess = 1 }) ) |])