Shellcheck: Spurious "In POSIX sh, RANDOM is undefined"

Created on 6 Jul 2018  路  3Comments  路  Source: koalaman/shellcheck

For bugs

  • SC2039
  • Shellversion version: 0.4.7
  • [X] I tried on 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/sh
test -n "$RANDOM" || echo OK

Here's what shellcheck currently says:

test.sh:2:10: warning: In POSIX sh, RANDOM is undefined. [SC2039]

Here's what I wanted or expected to see:

No warning, because test -n (or test -z) guards against the possibility of $RANDOM being empty, thus making it possible to write portable scripts that work safely in POSIX sh'.

Most helpful comment

I argue that an exception could be made for test -n and test -z on such variables. In some scripts, you are trying to test if the user has set an optional variable outside the script.

All 3 comments

Well it is not assigned in your example so the warning is fully legit.

I argue that an exception could be made for test -n and test -z on such variables. In some scripts, you are trying to test if the user has set an optional variable outside the script.

not sure about -z/-n usage, but allowing +set seems reasonable.

if [ "${RANDOM+set}" = "set" ]; then
  ...
fi

alternatively, if you're writing bash code, why not use a bash shebang to begin with ?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

arth1 picture arth1  路  4Comments

markscsmith picture markscsmith  路  5Comments

erichelgeson picture erichelgeson  路  5Comments

maxisme picture maxisme  路  3Comments

nathaniel112 picture nathaniel112  路  4Comments