shellcheck icon indicating copy to clipboard operation
shellcheck copied to clipboard

SC2164 false positive with cd at end of shell function

Open JarredAllen opened this issue 2 years ago • 6 comments

For bugs

  • Rule Id (if any, e.g. SC1000): SC2164
  • My shellcheck version (shellcheck --version or "online"): 0.7.0 (installed via apt)
  • [X] The rule's wiki page does not already cover this (e.g. https://shellcheck.net/wiki/SC2086)
  • [X] I tried on https://www.shellcheck.net/ and verified that this is still a problem on the latest commit

Here's a snippet or screenshot that shows the problem:

#!/bin/bash
..() {
        cd "$(for ((c=0; c<${1:-1}; ++c)); do echo -n ../; done)"
}

Here's what shellcheck currently says:

Line 4:
        cd "$(for ((c=0; c<${1:-1}; ++c)); do echo -n ../; done)"
        ^-- SC2164: Use 'cd ... || exit' or 'cd ... || return' in case cd fails.

Here's what I wanted or expected to see:

I expected no errors to happen because this can not cause an issue (the cd being at the end of the function means it can't continue on to anything else and a return there would be redundant).

JarredAllen avatar Mar 23 '22 03:03 JarredAllen

Ignore it with a directive, you have evaluated the case and are now ready to continue on.

brother avatar Mar 23 '22 09:03 brother

@brother That's a workaround for this issue, but I feel like that shouldn't be necessary for the reasons I outlined in my initial post.

JarredAllen avatar Mar 23 '22 16:03 JarredAllen

@JarredAllen and that will take some code in a PR. Very welcome contribution ofc, until then - ignore it.

brother avatar Mar 23 '22 19:03 brother

@brother That's a workaround for this issue, but I feel like that shouldn't be necessary for the reasons I outlined in my initial post.

+1

forthrin avatar Mar 02 '23 15:03 forthrin

Using BashSupport Pro. This is more simple false positive:

#!/usr/bin/env bash

pushd some-dir/ \
    && make \
    && echo "do stuff" \

popd

USSX-Hares avatar Aug 10 '23 10:08 USSX-Hares

A much more simple false positive is

#!/bin/bash

foo() {
  cd /abc
}
$ shellcheck /tmp/foo.sh

In /tmp/foo.sh line 4:
  cd /abc
  ^-----^ SC2164 (warning): Use 'cd ... || exit' or 'cd ... || return' in case cd fails.

$ shellcheck --version
ShellCheck - shell script analysis tool
version: 0.9.0

ensc avatar Jan 29 '24 17:01 ensc