Skip to content

Commit 1b59697

Browse files
authored
Merge pull request #3426 from notpeter/sc2164-false-positive
SC2164: suppress when `cd` is the final command in a function
2 parents 766a836 + 0648d5d commit 1b59697

1 file changed

Lines changed: 9 additions & 0 deletions

File tree

src/ShellCheck/Analytics.hs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3294,6 +3294,7 @@ prop_checkUncheckedPopd10 = verifyNotTree checkUncheckedCdPushdPopd "cd ../.."
32943294
prop_checkUncheckedPopd11 = verifyNotTree checkUncheckedCdPushdPopd "cd ../.././.."
32953295
prop_checkUncheckedPopd12 = verifyNotTree checkUncheckedCdPushdPopd "cd /"
32963296
prop_checkUncheckedPopd13 = verifyTree checkUncheckedCdPushdPopd "cd ../../.../.."
3297+
prop_checkUncheckedCdInFunction1 = verifyNotTree checkUncheckedCdPushdPopd "#!/bin/bash\nfoo() {\n cd /abc\n}"
32973298

32983299
checkUncheckedCdPushdPopd params root =
32993300
if hasSetE params then
@@ -3304,13 +3305,21 @@ checkUncheckedCdPushdPopd params root =
33043305
| name `elem` ["cd", "pushd", "popd"]
33053306
&& not (isSafeDir t)
33063307
&& not (name `elem` ["pushd", "popd"] && ("n" `elem` map snd (getAllFlags t)))
3308+
&& not (isLastCommandInFunction t)
33073309
&& not (isCondition $ getPath (parentMap params) t) =
33083310
warnWithFix (getId t) 2164
33093311
("Use '" ++ name ++ " ... || exit' or '" ++ name ++ " ... || return' in case " ++ name ++ " fails.")
33103312
(fixWith [replaceEnd (getId t) params 0 " || exit"])
33113313
where name = getName t
33123314
checkElement _ = return ()
33133315
getName t = fromMaybe "" $ getCommandName t
3316+
isLastCommandInFunction t =
3317+
go $ NE.tail $ getPath (parentMap params) t
3318+
where
3319+
go (child:T_BraceGroup _ commands:T_Function {}:_) =
3320+
not (null commands) && getId (last commands) == getId child
3321+
go (_:rest) = go rest
3322+
go [] = False
33143323
isSafeDir t = case oversimplify t of
33153324
[_, str] -> str `matches` regex
33163325
_ -> False

0 commit comments

Comments
 (0)