shellcheck icon indicating copy to clipboard operation
shellcheck copied to clipboard

if $variable; then should throw an error because it does not do what many inexperienced people expect it to do

Open artificial-intelligence opened this issue 1 year ago • 0 comments

For new checks and feature suggestions

  • [x] https://www.shellcheck.net/ (i.e. the latest commit) currently gives no useful warnings about this
  • [x] I searched through https://github.com/koalaman/shellcheck/issues and didn't find anything related

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


#!/bin/bash
is_true="yes"
if $is_true; then
echo "variable is $is_true";
fi

Here's what shellcheck currently says:

$ shellcheck myscript
No issues detected!

Here's what I wanted or expected to see:

Line 3:
if $is_true
  ^-- [SCFOOBAR](https://www.shellcheck.net/wiki/SCFOOBAR) (warning): Did you mean to test the content of a variable? use [[ "$is_true" == "foobar" ]] instead of `$is_true`. If you really want to run a command make sure it terminates.

This seems to be a common error made by python programmers who are not familiar with bash, to just check if the variable is set or they expect that a truth value is automatically carried over.

what instead happens, if a command like "yes" is the content of the variable, it get's executed indefinitely.

I think this can't be an error, because there is the legitimate usecase of putting commands in variables and then executing them - a common pattern is e.g. to construct a commandline via different variables which are concatenated together given different conditions.

But I think this at least should be an optional warning.

It's an ambiguous issue for sure.

Thanks for your consideration.

artificial-intelligence avatar Mar 14 '24 16:03 artificial-intelligence