17

shellcheck generated the following warning

SC2155: Declare and assign separately to avoid masking return
values

For this line of code

local key_value=$(echo "$current_line" | mawk '/.+=.+/ {print $1 }')

What does "masking return values" mean, and how does it pertain to the aforementioned warning?

1 Answers1

17

When you declare a variable as either local or exported that in itself is a command that will return success or not.

$ var=$(false)
$ echo $?
1
$ export var=$(false)
$ echo $?
0

So if you wanted to act on the return value of your command (echo "$current_line" | mawk '/.+=.+/ {print $1 }'), you would be unable to since it's going to exit with 0 as long as the local declaration succeeds (which is almost always will).

In order to avoid this it suggests declaring separately and then assigning:

local key_value
key_value=$(echo "$current_line" | mawk '/.+=.+/ {print $1 }')

This is a shellcheck rule I frequently ignore and IMO is safe to ignore as long as you know you aren't trying to act on the return value of that variable declaration.

You can ignore it by adding the following to the top of your script (Below the hashbang of course):

# shellcheck disable=SC2155
jesse_b
  • 35,934
  • 12
  • 91
  • 140
  • 3
    Folks determining whether their code is *"trying to act on the return value"* should keep in mind that having `set -e` or an ERR trap fire is also an action (though [I don't recommend their use regardless](http://mywiki.wooledge.org/BashFAQ/105#Exercises)). – Charles Duffy Mar 15 '19 at 02:38