POSIX One-Liner For Current Directory – Trying to make it pass ShellCheck

The one-liner from mklement0 in this discussion on POSIX-compliant scripts and getting the full path. It’s failing ShellCheck. Removing the space causes it to no longer work.
https://stackoverflow.com/questions/29832037/how-to-get-script-directory-in-posix-sh

dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
             ^-- SC1007: Remove space after = if trying to assign a value (for empty string, use var='' ... ).

Removing CDPATH= results in ShellCheck passing, and it still seems to work, but…

The CDPATH= prefix takes the place of > /dev/null in the original command: $CDPATH is set to a null string so as to ensure that cd never echoes anything.

Looks like it’s needed. So, is there any way to make this pass ShellCheck? Or just ignore it?

Asked By: rannday

||

Yes, you can specify a quoted empty value:

dir=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd)

as suggested by ShellCheck:

(for empty string, use var=” … )

Answered By: Stephen Kitt
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.