Skip to content

Commit a0a6301

Browse files
sunshinecogitster
authored andcommitted
t/check-non-portable-shell: detect "FOO=bar shell_func"
One-shot environment variable assignments, such as 'FOO' in "FOO=bar cmd", exist only during the invocation of 'cmd'. However, if 'cmd' happens to be a shell function, then 'FOO' is assigned in the executing shell itself, and that assignment remains until the process exits (unless explicitly unset). Since this side-effect of "FOO=bar shell_func" is unlikely to be intentional, detect and report such usage. To distinguish shell functions from other commands, perform a pre-scan of shell scripts named as input, gleaning a list of function names by recognizing lines of the form (loosely matching whitespace): shell_func () { and later report suspect lines of the form (loosely matching quoted values): FOO=bar [BAR=foo ...] shell_func Also take care to stitch together incomplete lines (those ending with "\") since suspect invocations may be split over multiple lines: FOO=bar BAR=foo \ shell_func Signed-off-by: Eric Sunshine <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent c433600 commit a0a6301

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

t/check-non-portable-shell.pl

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,24 +7,43 @@
77
use warnings;
88

99
my $exit_code=0;
10+
my %func;
1011

1112
sub err {
1213
my $msg = shift;
1314
s/^\s+//;
1415
s/\s+$//;
16+
s/\s+/ /g;
1517
print "$ARGV:$.: error: $msg: $_\n";
1618
$exit_code = 1;
1719
}
1820

21+
# glean names of shell functions
22+
for my $i (@ARGV) {
23+
open(my $f, '<', $i) or die "$0: $i: $!\n";
24+
while (<$f>) {
25+
$func{$1} = 1 if /^\s*(\w+)\s*\(\)\s*{\s*$/;
26+
}
27+
close $f;
28+
}
29+
1930
while (<>) {
2031
chomp;
32+
# stitch together incomplete lines (those ending with "\")
33+
while (s/\\$//) {
34+
$_ .= readline;
35+
chomp;
36+
}
37+
2138
/\bsed\s+-i/ and err 'sed -i is not portable';
2239
/\becho\s+-[neE]/ and err 'echo with option is not portable (use printf)';
2340
/^\s*declare\s+/ and err 'arrays/declare not portable';
2441
/^\s*[^#]\s*which\s/ and err 'which is not portable (use type)';
2542
/\btest\s+[^=]*==/ and err '"test a == b" is not portable (use =)';
2643
/\bwc -l.*"\s*=/ and err '`"$(wc -l)"` is not portable (use test_line_count)';
2744
/\bexport\s+[A-Za-z0-9_]*=/ and err '"export FOO=bar" is not portable (use FOO=bar && export FOO)';
45+
/^\s*([A-Z0-9_]+=(\w+|(["']).*?\3)\s+)+(\w+)/ and exists($func{$4}) and
46+
err '"FOO=bar shell_func" assignment extends beyond "shell_func"';
2847
# this resets our $. for each file
2948
close ARGV if eof;
3049
}

0 commit comments

Comments
 (0)