blib/lib/BATsh/SH.pm untested

filter: Statementstmt 0.0% 0 / 5096 Branchbran 0.0% 0 / 2662 Conditioncond 0.0% 0 / 1623 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 205 Podpod 0.0% 0 / 179 totaltotal 0.0% 0 / 9765 SCAR 143.9
CC
1332
Cov
0%
_exec_line_impl
3906.0
_eval_test
2970.0
_parse_subshell
1560.0
CRAP 1775556.0
1 package BATsh::SH;
2 ######################################################################
3 #
4 # BATsh::SH - Pure Perl sh/bash interpreter
5 #
6 # Copyright (c) 2026 INABA Hitoshi <ina.cpan@gmail.com>
7 #
8 # Implements sh/bash command set in Perl.
9 # No external sh or bash required.
10 #
11 # Supported:
12 # Variable assignment: VAR=value
13 # export VAR=value, export VAR, unset VAR
14 # echo, printf
15 # if/then/elif/else/fi
16 # for VAR in list; do ... done
17 # while condition; do ... done
18 # until condition; do ... done
19 # case $var in pat|pat) ... ;; *) ... ;; esac (|, globs, [classes], ;& ;;&)
20 # test / [ ... ] (file, string, integer comparisons)
21 # cd, pwd, exit, true, false, :
22 # trap 'cmd' SIG... / trap - SIG / trap '' SIG / trap [-p] (EXIT + %SIG bridge)
23 # read VAR (reads one line from STDIN)
24 # shift [N] (shift positional parameters left)
25 # local VAR=value (function-scoped variable)
26 # $(( arithmetic )) -- +,-,*,/,%, and $1..$9 inside
27 # $( command ) and `command` (command substitution, nested)
28 # name() { ... }, function name { ... } (function definitions)
29 # cmd1 | cmd2 [| cmd3 ...] (pipeline via tmpfile, 5.005_03)
30 # cmd1 && cmd2, cmd1 || cmd2, cmd1 ; cmd2 (compound commands)
31 # > >> < 2> 2>> 2>&1 1>&2 (I/O redirection)
32 # cmd << DELIM ... DELIM, <<-DELIM, <<'DELIM' (here-document)
33 # cmd & (background execution of an external command; SH mode)
34 # $VAR, ${VAR}, $1..$9, $@, $*, $#, $?, $$, $0, $!
35 # ${VAR:-def}, ${VAR:=def}, ${VAR:+alt}
36 # ${VAR%pat}, ${VAR%%pat} (shortest/longest suffix removal)
37 # ${VAR#pat}, ${VAR##pat} (shortest/longest prefix removal)
38 # ${VAR/pat/rep}, ${VAR//pat/rep} (first/all substitution)
39 # ${VAR^^}, ${VAR^}, ${VAR,,}, ${VAR,} (case conversion)
40 # ${VAR:N:L}, ${VAR:N} (substring)
41 # ${#VAR} (string length)
42 # arr=(a b c), arr+=(d e) (indexed array assignment / append)
43 # arr[i]=v, arr[i]+=v (indexed element assignment / append)
44 # declare -a arr, declare -A map, typeset ... (array declaration)
45 # map=([k1]=v1 [k2]=v2), map[k]=v (associative array assignment)
46 # ${arr[i]}, ${map[key]} (element access; $arr == ${arr[0]})
47 # ${arr[@]}, ${arr[*]} (all elements)
48 # ${#arr[@]}, ${#map[@]} (element count)
49 # ${#arr[i]} (length of one element)
50 # ${!arr[@]}, ${!map[@]} (indices / keys)
51 # unset arr, unset arr[i] (whole array / single element)
52 # source / . file
53 # {a,b,c}, {1..5}, {a..e}[..step] (brace expansion, v0.07)
54 # shopt -s/-u extglob; ?(),*(),+(),@(),!() (extended pattern matching
55 # in case patterns and ${VAR%pat}-family patterns, v0.07)
56 # cmd <<< word (here-string, v0.07)
57 # <(cmd), >(cmd) (process substitution via temp file, v0.07)
58 # select VAR in list; do ... done (menu loop, v0.07)
59 # alias name=value, alias, unalias (v0.07)
60 # exec cmd, exec > file ... (v0.07)
61 # ( cmd1; cmd2 ) (subshell command group with isolated scope, v0.07)
62 #
63 ######################################################################
64  
65 use strict;
66 BEGIN { if ($] < 5.006 && !defined(&warnings::import)) { $INC{'warnings.pm'} = 'stub'; eval 'package warnings; sub import {}' } }
67 use warnings; local $^W = 1;
68 BEGIN { pop @INC if $INC[-1] eq '.' }
69  
70 use File::Spec ();
71 use Carp qw(croak);
72 use Fcntl qw(O_RDONLY O_WRONLY O_CREAT O_EXCL O_TRUNC O_APPEND);
73 use vars qw($VERSION);
74 $VERSION = '0.10';
75 $VERSION = $VERSION;
76  
77 require BATsh::MB;
78  
79 # Bareword filehandle globs for SH pipeline (Perl 5.005_03 compatible)
80 use vars qw(*_SH_PIPE_SAVOUT *_SH_PIPE_SAVIN *_SH_PIPE_WFH *_SH_PIPE_RFH);
81  
82 # Bareword filehandle globs for SH I/O redirection (Perl 5.005_03 compatible)
83 use vars qw(*_SH_REDIR_SRC *_SH_REDIR_DST *_SH_REDIR_SAVOUT *_SH_REDIR_SAVERR *_SH_REDIR_SAVIN);
84  
85 # Bareword filehandle glob for here-document temp file (Perl 5.005_03 compatible)
86 use vars qw(*_HD_TMP);
87  
88 # Bareword directory handle for pathname expansion (_glob_paths). One
89 # directory level is read and closed at a time, so a single handle is
90 # enough and is never nested.
91 use vars qw(*_GLOB_DH);
92  
93 # Bareword filehandle globs for background-job PID temp file (Perl 5.005_03 compatible)
94 use vars qw(*_BG_TMP *_BG_PIDFH);
95  
96 # $! -- PID of the most recent background job (package-level so _expand and
97 # the test suite can read it). Empty string before any background job.
98 use vars qw($_LAST_BG_PID);
99 $_LAST_BG_PID = '';
100  
101 # Active nesting depth of command substitution _cmd_subst(). Each active
102 # level uses a distinct capture temp file so that a nested $( ... $( ... ) )
103 # does not truncate/unlink the file the outer level is still capturing into.
104 # (Sequential, non-overlapping substitutions safely reuse the same depth.)
105 use vars qw($_SUBST_DEPTH);
106 $_SUBST_DEPTH = 0;
107  
108 # Active nesting depth of pipeline execution _exec_sh_pipe(). A pipeline
109 # segment may itself contain a $(...) whose body is another pipeline; each
110 # active pipeline must use distinct stage temp files so the inner pipeline
111 # does not clobber/unlink the outer pipeline's stage file (which would leave
112 # the outer's final segment reading from the real STDIN and hanging).
113 use vars qw($_PIPE_DEPTH);
114 $_PIPE_DEPTH = 0;
115  
116 # SH function registry -- must be package-level for access from _expand and _exec_line
117 use vars qw(%_SH_FUNCTIONS);
118  
119 # SH alias registry (v0.07). NAME (case-sensitive, as bash) => raw
120 # replacement text. Populated by the "alias" builtin, consumed by
121 # _alias_expand_line() at the top of _exec_line().
122 use vars qw(%_SH_ALIAS);
123  
124 # Variable attribute registries (v0.08). Keyed by the UPPERCASED variable
125 # name (matching BATsh::Env's case-insensitive store). %_SH_READONLY marks
126 # a variable read-only ("readonly" / "declare -r"); a later assignment is
127 # refused with a diagnostic and non-zero status. %_SH_INTATTR marks the
128 # integer attribute ("declare -i"); an assignment then evaluates its right
129 # hand side as shell arithmetic.
130 use vars qw(%_SH_READONLY %_SH_INTATTR);
131  
132 # Shell umask (v0.08). Native Win32 Perl's umask() is effectively a no-op
133 # (it always reports 0), so the shell keeps its OWN notion of the mask so
134 # that "umask MODE; umask" round-trips on every platform. It is seeded
135 # once from the real process umask (meaningful on Unix-like systems) and,
136 # on a set, is also pushed to the OS umask so it still affects file modes
137 # where the OS honours it.
138 use vars qw($_SH_UMASK $_SH_UMASK_INIT);
139 $_SH_UMASK_INIT = 0;
140  
141 # Process-substitution bookkeeping (v0.07). <(cmd) is captured eagerly
142 # into a temp file during _expand(); >(cmd) defers cmd until after the
143 # current simple command finishes. Both use unique sysopen(O_CREAT|
144 # O_EXCL) temp files, mirroring _hd_tempfile() / _subst_tempfile().
145 use vars qw($_PROCSUB_SEQ @_PROCSUB_TMPFILES @_PROCSUB_DEFERRED);
146 $_PROCSUB_SEQ = 0;
147 @_PROCSUB_TMPFILES = ();
148 @_PROCSUB_DEFERRED = ();
149  
150 # SH array storage (v0.06). Indexed and associative arrays.
151 # %_SH_ARRAY : NAME (uppercased) => hashref { subscript => value }
152 # %_SH_ARRAY_TYPE : NAME (uppercased) => 'indexed' | 'assoc'
153 # Array names are case-insensitive (stored uppercase) to match the scalar
154 # store. Indexed arrays may be sparse; subscripts are integer strings.
155 # Associative arrays use arbitrary string subscripts. Element order for
156 # ${arr[@]} is ascending numeric index (indexed) or ascending key sort
157 # (assoc) -- the latter is chosen for deterministic output across Perl
158 # versions, since bash leaves associative-array order unspecified.
159 use vars qw(%_SH_ARRAY %_SH_ARRAY_TYPE);
160  
161 # SH trap registry (v0.06). Maps a normalized signal name (e.g. INT, TERM,
162 # EXIT) to the raw command string to run when that signal/event fires. An
163 # empty string means "ignore"; absence means "default". Real signals are
164 # bridged to Perl's %SIG (see _sh_set_os_sig); the EXIT pseudo-signal is run
165 # internally when the script exits (see fire_exit_trap / _cmd_exit).
166 use vars qw(%_SH_TRAP);
167  
168 # getopts state (v0.07). POSIX getopts tracks its position across the
169 # argument list with the OPTIND shell variable (1-based, stored in the
170 # Env), but the offset of the next option CHARACTER inside a clustered
171 # argument such as "-abc" is internal state that the shell does not
172 # expose. We keep that character offset in $_GETOPTS_CHARPOS and detect
173 # an external reset of the loop (the script setting OPTIND=1 before a
174 # fresh getopts loop) by remembering, in $_GETOPTS_LAST_OPTIND, the
175 # OPTIND value getopts itself last stored: if the OPTIND we read back
176 # differs, the caller reset the loop and the character offset restarts.
177 use vars qw($_GETOPTS_CHARPOS $_GETOPTS_LAST_OPTIND);
178 $_GETOPTS_CHARPOS = 0;
179 $_GETOPTS_LAST_OPTIND = 0;
180  
181 # "command NAME ..." bypass flag (v0.08). The POSIX "command" builtin runs
182 # NAME as if no shell function of that name existed. _cmd_command() localizes
183 # this to 1 around the re-dispatch of the raw remainder so that the
184 # function-lookup gate in _exec_line_impl() is skipped for that one command
185 # (builtins and external programs are unaffected, exactly as bash does).
186 use vars qw($_CMD_NO_FUNC);
187 $_CMD_NO_FUNC = 0;
188 # ----------------------------------------------------------------
189 my $LAST_STATUS = 0; # $?
190  
191 # Shell options (set -e / -u / -x), process-persistent like the Env store;
192 # reset by reset_sh_options() at the start of each top-level run.
193 my $_OPT_ERREXIT = 0; # set -e: exit on a failing simple command
194 my $_OPT_NOUNSET = 0; # set -u: error on expanding an unset variable
195 my $_OPT_XTRACE = 0; # set -x: trace each simple command to STDERR
196 my $_OPT_EXTGLOB = 0; # shopt -s extglob: ?(),*(),+(),@(),!() in patterns
197 my $_ERREXIT_HOLD = 0; # >0: -e suppressed (condition / non-final &&-|| member)
198 my $_ERREXIT_DONE = 0; # set by _exec_sh_compound: -e already adjudicated
199 my @FUNCTION_STACK = (); # for 'local' variable scoping
200  
201 # Signal: pending exit
202 my $_EXIT_CODE = undef; # undef = no exit pending
203 my $_BREAK = 0; # break out of loop
204 my $_CONTINUE = 0; # continue next iteration
205 my $_RETURN = 0; # return from function/source
206  
207 # Here-document state (Perl 5.005_03 compatible)
208 my $_HD_SEQ = 0; # per-process counter for unique temp names
209 my @_HD_TMPFILES = (); # tempfiles to remove on END (failsafe cleanup)
210  
211 # Background-job state (Perl 5.005_03 compatible)
212 my $_BG_SEQ = 0; # per-process counter for unique pidfile names
213 my @_BG_TMPFILES = (); # pidfiles to remove on END (failsafe cleanup)
214  
215 # Command-substitution capture state (Perl 5.005_03 compatible)
216 my $_SUBST_SEQ = 0; # per-process counter for unique capture names
217 my @_SUBST_TMPFILES = (); # capture files to remove on END (failsafe cleanup)
218  
219 # SH pipeline stage state (Perl 5.005_03 compatible)
220 my $_PIPE_SEQ = 0; # per-process counter for unique stage names
221 my @_SHP_TMPFILES = (); # stage files to remove on END (failsafe cleanup)
222  
223 # ----------------------------------------------------------------
224 # Public: execute an array of SH lines
225 # Returns exit status (0 = success)
226 # ----------------------------------------------------------------
227 # ----------------------------------------------------------------
228 # get_status / set_status: read or set the SH-side $? from outside
229 # the interpreter. Used by BATsh.pm to bridge $? <-> %ERRORLEVEL%
230 # at every CMD<->SH section boundary. Call as plain functions.
231 # ----------------------------------------------------------------
232 sub get_status { return $LAST_STATUS }
233 sub set_status {
234 $LAST_STATUS = defined $_[0] ? int($_[0]) : 0;
235 return $LAST_STATUS;
236 }
237  
238 # ----------------------------------------------------------------
239 # exit_code_pending: the exit code set by the SH "exit" builtin in the
240 # most recent exec_block, or undef when no exit was executed. The value
241 # stays readable until the next exec_block resets it; BATsh.pm reads it
242 # right after each SH block to terminate the whole script.
243 # ----------------------------------------------------------------
244 sub exit_code_pending { return $_EXIT_CODE }
245  
246 sub exec_block {
247 my ($class, $lines_ref, %opts) = @_;
248 $_EXIT_CODE = undef;
249 $_BREAK = 0;
250 $_CONTINUE = 0;
251 $_RETURN = 0;
252  
253 my $status = _run_lines($class, $lines_ref, \%opts);
254 return defined $_EXIT_CODE ? $_EXIT_CODE : $status;
255 }
256  
257 # ----------------------------------------------------------------
258 # Run an array of lines sequentially, handling multi-line blocks
259 # Returns last exit status
260 # ----------------------------------------------------------------
261 sub _run_lines {
262 my ($class, $lines_ref, $opts_ref) = @_;
263 my @lines = @{$lines_ref};
264 my $status = 0;
265 my $i = 0;
266  
267 while ($i <= $#lines) {
268 return $status if defined $_EXIT_CODE;
269 return $status if $_BREAK || $_RETURN;
270  
271 my $line = $lines[$i];
272 $i++;
273 # Normalise
274 $line =~ s/\r?\n\z//;
275 # Strip a trailing "# comment" (word-initial, unquoted) and write
276 # the cleaned line back so downstream block parsers see it too.
277 my $nocmt = _strip_sh_comment($line);
278 if ($nocmt ne $line) { $line = $nocmt; $lines[$i - 1] = $line; }
279 # Skip empty and comment lines
280 next if $line =~ /\A\s*\z/;
281 next if $line =~ /\A\s*#/;
282  
283 # Check for block-opening keywords
284 my $stripped = $line;
285 $stripped =~ s/\A\s+//;
286 my $first = '';
287 ($first) = ($stripped =~ /\A(\S+)/);
288 $first = lc(defined($first) ? $first : '');
289  
290 if ($first eq 'if') {
291 ($status, $i) = _parse_if($class, \@lines, $i - 1, $opts_ref);
292 next;
293 }
294 if ($first eq 'for') {
295 ($status, $i) = _parse_for($class, \@lines, $i - 1, $opts_ref);
296 next;
297 }
298 if ($first eq 'select') {
299 ($status, $i) = _parse_select($class, \@lines, $i - 1, $opts_ref);
300 next;
301 }
302 if ($first eq 'while' || $first eq 'until') {
303 ($status, $i) = _parse_while($class, \@lines, $i - 1, $opts_ref);
304 next;
305 }
306 if ($first eq 'case') {
307 ($status, $i) = _parse_case($class, \@lines, $i - 1, $opts_ref);
308 next;
309 }
310  
311 # Subshell command group: "( commands )" [redir]. A leading "(("
312 # is arithmetic-expansion-flavoured, not a subshell group, and is
313 # left alone (standalone "((...))" arithmetic commands are not
314 # implemented; only "$((...))" as an expansion is).
315 if ($stripped =~ /\A\(/ && $stripped !~ /\A\(\(/) {
316 ($status, $i) = _parse_subshell($class, \@lines, $i - 1, $opts_ref);
317 next;
318 }
319  
320 # Function definition: "name() {" or "function name {"
321 if ($stripped =~ /\A(?:function\s+[A-Za-z_]|[A-Za-z_][A-Za-z0-9_]*\s*\(\s*\))/) {
322 ($status, $i) = _parse_function($class, \@lines, $i - 1, $opts_ref);
323 next;
324 }
325  
326 # Here-document: cmd << [-] [QUOTE]DELIM[QUOTE]
327 # Detected on a simple command line; body is read from following
328 # lines up to a line equal to DELIM (after optional tab strip for <<-).
329 my @hd = _hd_detect($line);
330 if (@hd) {
331 my ($cmd_part, $dash, $delim, $quoted) = @hd;
332 my @body = ();
333 my $terminated = 0;
334 while ($i <= $#lines) {
335 my $bl = $lines[$i];
336 $i++;
337 $bl =~ s/\r?\n\z//;
338 my $probe = $bl;
339 $probe =~ s/\A\t+// if $dash; # <<- strips leading tabs
340 if ($probe eq $delim) { $terminated = 1; last }
341 $bl =~ s/\A\t+// if $dash; # also strip tabs from body
342 push @body, $bl;
343 }
344 if (!$terminated) {
345 warn "sh: unexpected EOF while looking for here-document delimiter \`$delim'\n";
346 $LAST_STATUS = 2;
347 $status = 2;
348 next;
349 }
350 $status = _hd_run($class, $cmd_part, \@body, $quoted, $opts_ref);
351 next;
352 }
353  
354 # A simple-command prefix followed on the SAME physical line by a
355 # control structure introduced with ';' -- e.g.
356 # x=""; if [ -z "$x" ]; then echo empty; fi
357 # i=0; while [ $i -lt 3 ]; do ...; done
358 # v=cat; case $v in ...; esac
359 # The first token is not a control keyword, so the block-opener
360 # dispatch above did not fire. Run the prefix now, then rewrite
361 # the current slot to the control structure and reprocess it, so
362 # the proper _parse_* handles it (and may consume following
363 # physical lines for a multi-line body).
364 my $ctl_off = _find_control_split($line);
365 if (defined $ctl_off) {
366 my $prefix = substr($line, 0, $ctl_off);
367 my $rest = substr($line, $ctl_off);
368 $prefix =~ s/\s*;\s*\z//;
369 if ($prefix =~ /\S/) {
370 $_ERREXIT_DONE = 0;
371 $status = _exec_line($class, $prefix, $opts_ref);
372 _errexit_check($status) unless $_ERREXIT_DONE;
373 $_ERREXIT_DONE = 0;
374 }
375 last if defined $_EXIT_CODE || $_BREAK || $_RETURN;
376 $lines[$i - 1] = $rest;
377 $i--;
378 next;
379 }
380  
381 $_ERREXIT_DONE = 0;
382 $status = _exec_line($class, $line, $opts_ref);
383 _errexit_check($status) unless $_ERREXIT_DONE;
384 $_ERREXIT_DONE = 0;
385 $_CONTINUE = 0 if $_CONTINUE;
386 }
387 return $status;
388 }
389  
390 # ----------------------------------------------------------------
391 # Execute one SH line
392 # ----------------------------------------------------------------
393 # _exec_line: thin wrapper around _exec_line_impl() that drains any
394 # process-substitution bookkeeping (v0.07) added while executing THIS
395 # call's line -- running deferred >(cmd) jobs and removing <(cmd) temp
396 # files -- after the simple command has run. Because _exec_line_impl()
397 # itself calls back into _exec_line() (never _exec_line_impl() directly)
398 # for background execution, redirection wrapping, compound/pipeline
399 # segments, and exec, each nesting level drains only the entries it
400 # introduced, using the before/after array-length markers below.
401 # ----------------------------------------------------------------
402 sub _exec_line {
403 my ($class, $raw, $opts_ref) = @_;
404 my $tmp_before = scalar(@_PROCSUB_TMPFILES);
405 my $def_before = scalar(@_PROCSUB_DEFERRED);
406 my $rc = _exec_line_impl($class, $raw, $opts_ref);
407 if (@_PROCSUB_DEFERRED > $def_before) {
408 my @jobs = splice(@_PROCSUB_DEFERRED, $def_before);
409 for my $job (@jobs) {
410 my ($tmp, $cmd) = @{$job};
411 _sh_exec_with_redirs($class, $cmd, [[0, 0, $tmp]], $opts_ref);
412 }
413 }
414 if (@_PROCSUB_TMPFILES > $tmp_before) {
415 my @files = splice(@_PROCSUB_TMPFILES, $tmp_before);
416 for my $f (@files) { unlink $f if defined $f }
417 }
418 return $rc;
419 }
420  
421 sub _exec_line_impl {
422 my ($class, $raw, $opts_ref) = @_;
423  
424 my $line = $raw;
425 $line =~ s/\A\s+//;
426 return 0 if $line =~ /\A\s*\z/;
427 return 0 if $line =~ /\A\s*#/;
428  
429 # Shebang: treat as comment
430 return 0 if $line =~ /\A#!/;
431  
432 # Alias expansion (v0.07): replace a leading command word that names
433 # an active alias with its stored text, re-checking the new leading
434 # word up to a small bounded number of times so that alias chains
435 # (alias ll=ls; alias ls='ls -la') resolve. A name is expanded at
436 # most once per line to guard against a self-referential alias
437 # (alias ls=ls) looping forever. Only the first word of the line is
438 # considered -- bash's "trailing space in the alias value also makes
439 # the next word alias-eligible" refinement is not modelled.
440 $line = _alias_expand_line($line);
441  
442 # Brace expansion (v0.07): {a,b,c} and {1..5}/{a..e} word-generation,
443 # performed lexically on the raw line before any other expansion, so
444 # that e.g. "echo a{b,c}d" becomes two arguments "abd acd". Regions
445 # that are quoted, or that belong to ${...}/$(...)/$((...))/`...`,
446 # are left untouched (their braces/parens are not brace-expansion
447 # syntax).
448 $line = _brace_expand_line($line);
449  
450 # ----------------------------------------------------------------
451 # Background execution: an unquoted trailing & (v1).
452 # Detected here, BEFORE _split_sh_compound, so that the bare & is
453 # never mistaken for && and so that an internal & (e.g. in 2>&1 or
454 # >&2) is left untouched. Only the single & at the very end of the
455 # line is consumed. Builtins / functions / control words / variable
456 # assignments run in the FOREGROUND (the & is ignored); only external
457 # commands are launched asynchronously.
458 # ----------------------------------------------------------------
459 my ($_is_bg, $_bg_line) = _split_trailing_bg($line);
460 if ($_is_bg) {
461 $line = $_bg_line;
462 my $probe = $line;
463 $probe =~ s/\A\s+//;
464 my $w0 = '';
465 ($w0) = ($probe =~ /\A(\S+)/);
466 $w0 = '' unless defined $w0;
467 if (_sh_word_is_foreground($w0)) {
468 # & ignored: run the stripped line in the foreground.
469 return _exec_line($class, $line, $opts_ref);
470 }
471 my $exp = _expand($class, $line);
472 $exp =~ s/\A\s+//;
473 $exp =~ s/\s+\z//;
474 return _bg_launch($class, $exp);
475 }
476  
477 # Detect && / || / ; compound commands BEFORE expansion.
478 # These must be split before _expand so that short-circuit logic works.
479 my @compound = _split_sh_compound($line);
480 if (@compound > 1) {
481 return _exec_sh_compound($class, \@compound, $opts_ref);
482 }
483  
484 # set -x: trace the simple command to STDERR (the raw, pre-expansion
485 # line -- expanding a copy here would run $(...) substitutions twice).
486 print STDERR '+ ', BATsh::MB::dec($line), "\n" if $_OPT_XTRACE;
487  
488 # Detect pipeline BEFORE variable expansion to avoid expanding
489 # pipe-like characters inside command substitutions prematurely.
490 # _split_sh_pipe returns >1 segment only when bare | is present.
491 my @pipe_segs = _split_sh_pipe($line);
492 if (@pipe_segs > 1) {
493 return _exec_sh_pipe($class, \@pipe_segs, $opts_ref);
494 }
495  
496 # A single control/compound command (while/for/if/until/case/select or
497 # a "( subshell )") may reach here as a pipeline element or && / ||
498 # operand -- e.g. the right side of cmd | while read x; do ...; done,
499 # or true && for i in ..; do ..; done. Route it through the block
500 # runner so its inline ';'-separated body is parsed by the proper
501 # _parse_* handler instead of being split and exec'd as external words.
502 if (_seg_is_control($line)) {
503 my @one = ($line);
504 return _run_lines($class, \@one, $opts_ref);
505 }
506  
507 # Array / associative-array operations (v0.06). Detected on the RAW line
508 # (before _expand) so that the "(a b c)" literal and the "[sub]" subscripts
509 # are not mangled by variable / command-substitution expansion.
510 {
511 my @h = _sh_try_array_op($class, $line, $opts_ref);
512 return $h[1] if @h;
513 }
514  
515 # trap (v0.06). Detected on the RAW line so that the handler command is
516 # captured literally and (re-)expanded only when the trap fires, matching
517 # shell semantics for e.g. trap 'rm $tmp' EXIT.
518 {
519 my $probe = $line;
520 $probe =~ s/\A\s+//;
521 if ($probe =~ /\Atrap(\s.*|)\z/is && $probe !~ /\Atrap\s*=/) {
522 return _cmd_trap($class, $1, $opts_ref);
523 }
524 }
525  
526 # POSIX assignment prefix on the RAW line: `VAR=value command args`.
527 # Detected before expansion so that a value containing $(...) or quoted
528 # spaces is not mistaken for a trailing command. Pure assignments (no
529 # command following) fall through to the post-expansion handler below.
530 {
531 my ($pairs_ref, $remainder) = _sh_assign_prefix($line);
532 if ($pairs_ref && defined $remainder && $remainder ne '') {
533 my $ro_fail = 0;
534 for my $p (@{$pairs_ref}) {
535 my ($var, $rawval) = @{$p};
536 my $val = _arr_dequote(_expand($class, $rawval));
537 $ro_fail = 1 unless _sh_store_scalar($var, $val);
538 }
539 if ($ro_fail) { $LAST_STATUS = 1; return 1 }
540 return _exec_line($class, $remainder, $opts_ref);
541 }
542 }
543  
544 # Keep the pre-expansion text around. It is used below (echo) to
545 # decide whether filename globbing should even be attempted: that
546 # decision must be based on glob metacharacters that were literally
547 # present in the source line, never on characters that merely ended
548 # up looking like "*", "?" or "[" because a variable's *value*
549 # happened to contain them (e.g. a getopts "?"/":" result). This is
550 # the same principle the tilde-prepass above already relies on:
551 # expansion results are not themselves subject to re-expansion.
552 my $_raw_pre_expand = $line;
553  
554 # Expand variables and command substitutions
555 $line = _expand($class, $line);
556  
557 # Strip trailing ;
558 $line =~ s/\s*;\s*\z//;
559  
560 # exec (v0.07): "exec > file" (etc.) applies its redirections
561 # permanently to the current shell (no restore); "exec cmd ..." runs
562 # cmd with those redirections and then terminates the whole script
563 # with cmd's exit status, approximating process replacement without
564 # a real fork/exec (this interpreter has no fork, by design -- see
565 # the pipeline / background-job implementation notes above).
566 if ($line =~ /\Aexec(?:\s+(.*)|\s*)\z/is) {
567 my $exec_rest = defined $1 ? $1 : '';
568 return _cmd_exec($class, $exec_rest, $opts_ref);
569 }
570  
571 # Here-string: cmd <<< word (v0.07). Detected after expansion (the
572 # word is fully variable/command/arithmetic-expanded, like any other
573 # word) and turned into an ordinary "< tempfile" stdin redirection,
574 # reusing the here-document temp-file machinery.
575 {
576 my ($hs_line, $hs_content) = _sh_strip_herestring($line);
577 if (defined $hs_content) {
578 my $tmp = _hd_tempfile($hs_content . "\n");
579 if (!defined $tmp) { $LAST_STATUS = 2; return 2 }
580 my ($clean_line, $redirs_ref) = _sh_strip_redirects($hs_line);
581 unshift @{$redirs_ref}, [0, 0, $tmp]
582 unless grep { $_->[0] == 0 } @{$redirs_ref};
583 my $rc = _sh_exec_with_redirs($class, $clean_line, $redirs_ref, $opts_ref);
584 unlink $tmp;
585 @_HD_TMPFILES = grep { $_ ne $tmp } @_HD_TMPFILES;
586 return $rc;
587 }
588 }
589  
590 # Detect I/O redirections: >, >>, <, 2>, 2>>, 2>&1
591 # Must be done after expansion so that variable-in-filename works.
592 my ($clean_line, $sh_redirs_ref) = _sh_strip_redirects($line);
593 if (@{$sh_redirs_ref}) {
594 return _sh_exec_with_redirs($class, $clean_line, $sh_redirs_ref, $opts_ref);
595 }
596 $line = $clean_line;
597  
598 my ($cmd, $rest) = _split_sh($line);
599 return 0 unless defined $cmd && $cmd ne '';
600  
601 my $lc_cmd = lc($cmd);
602  
603 # Pure assignment: VAR=value (no spaces around =). Assignment prefixes
604 # of the form `VAR=value command` were already handled before expansion,
605 # so anything reaching here is a standalone assignment. Match the whole
606 # (expanded) line so values containing spaces are preserved in full.
607 if ($line =~ /\A([A-Za-z_][A-Za-z0-9_]*)=(.*)\z/s) {
608 my ($var, $val) = ($1, $2); # capture before $1 is clobbered
609 # Dequote the value the same way command words are dequoted, so
610 # concatenated quotes (a"b"c, x'y'z) and backslash escapes resolve
611 # correctly -- not just a single outermost "..." / '...' pair.
612 $val = _arr_dequote($val);
613 my $ok = _sh_store_scalar($var, $val);
614 $LAST_STATUS = $ok ? 0 : 1;
615 return $ok ? 0 : 1;
616 }
617  
618 if ($lc_cmd eq 'export') { return _cmd_export($rest) }
619 if ($lc_cmd eq 'unset') { return _cmd_unset($rest) }
620 if ($lc_cmd eq 'echo') {
621 # Apply word-splitting and glob expansion to unquoted tokens
622 # (tilde expansion already happened earlier, in _expand()).
623 #
624 # Whether to glob at all is decided from the RAW, pre-expansion
625 # source text -- NOT from the already-expanded $rest. By this
626 # point $rest has had all $VAR / ${VAR} / $(...) substitutions
627 # applied, so a variable whose *value* happens to be "?" (as
628 # getopts sets $opt on an unknown option, or ":" on a missing
629 # argument) would otherwise be indistinguishable from a literal
630 # "?" glob pattern typed in the script -- and get run through
631 # _parse_args()/glob() against the current directory, silently
632 # replacing the echoed value with whatever 1-character filename
633 # happened to match. Checking the raw text instead means only
634 # a glob metacharacter that was actually written in the source
635 # (e.g. "echo *.txt") triggers globbing.
636 my @raw_parts = _split_sh($_raw_pre_expand);
637 my $raw_rest = $raw_parts[1];
638 $raw_rest = '' unless defined $raw_rest;
639 if (_raw_has_glob($raw_rest)) {
640 my @words = _parse_args($rest, 1);
641 $rest = join(' ', @words);
642 }
643 return _cmd_echo($rest);
644 }
645 if ($lc_cmd eq 'printf') { return _cmd_printf($rest) }
646 if ($lc_cmd eq 'cd') { return _cmd_cd($rest) }
647 if ($lc_cmd eq 'pwd') { print Cwd::cwd(), "\n"; return 0 }
648 if ($lc_cmd eq 'exit') { return _cmd_exit($rest) }
649 if ($lc_cmd eq 'true') { $LAST_STATUS = 0; return 0 }
650 if ($lc_cmd eq 'false') { $LAST_STATUS = 1; return 1 }
651 if ($lc_cmd eq ':') { $LAST_STATUS = 0; return 0 }
652 if ($lc_cmd eq 'read') { return _cmd_read($rest) }
653 if ($lc_cmd eq 'test' || $cmd eq '[') { return _cmd_test($rest) }
654 if ($lc_cmd eq 'source' || $cmd eq '.') { return _cmd_source($class, $rest, $opts_ref) }
655 if ($lc_cmd eq 'return') { $_RETURN = 1; $LAST_STATUS = ($rest =~ /\A\s*(\d+)/) ? int($1) : 0; return $LAST_STATUS }
656 if ($lc_cmd eq 'break') { $_BREAK = 1; return 0 }
657 if ($lc_cmd eq 'continue') { $_CONTINUE = 1; return 0 }
658 if ($lc_cmd eq 'shift') { return _cmd_shift($rest) }
659 if ($lc_cmd eq 'getopts') { return _cmd_getopts($rest) }
660 if ($lc_cmd eq 'local') { return _cmd_local($rest) }
661 if ($lc_cmd eq 'set') { return _cmd_set_sh($rest) }
662 if ($lc_cmd eq 'shopt') { return _cmd_shopt($rest) }
663 if ($lc_cmd eq 'alias') { return _cmd_alias($rest) }
664 if ($lc_cmd eq 'unalias') { return _cmd_unalias($rest) }
665 if ($lc_cmd eq 'eval') {
666 # POSIX eval: the (already expanded) arguments are stripped of one
667 # level of quoting, concatenated, and executed as a new command
668 # line -- which re-parses and re-expands, giving the double
669 # expansion eval exists for. "eval" with no arguments is a noop.
670 if (!defined $rest || $rest =~ /\A\s*\z/) { $LAST_STATUS = 0; return 0 }
671 my @words = _parse_args($rest);
672 return _exec_line($class, join(' ', @words), $opts_ref);
673 }
674 if ($lc_cmd eq 'let') { return _cmd_let($rest) }
675 if ($lc_cmd eq 'type') { return _cmd_type($rest) }
676 if ($lc_cmd eq 'command') {
677 # The introspection forms (-v / -V) are pure lookups; the plain
678 # run form re-dispatches the RAW (pre-expansion) remainder so it is
679 # expanded exactly once and shell functions of the same name are
680 # bypassed. Passing $_raw_pre_expand keeps expansion single-pass.
681 return _cmd_command($class, $rest, $_raw_pre_expand, $opts_ref);
682 }
683 if ($lc_cmd eq 'umask') { return _cmd_umask($rest) }
684 if ($lc_cmd eq 'hash') { return _cmd_hash($rest) }
685 if ($lc_cmd eq 'readonly') { return _cmd_readonly($class, $rest) }
686 if ($lc_cmd eq 'mapfile' || $lc_cmd eq 'readarray') {
687 return _cmd_mapfile($class, $rest);
688 }
689  
690 # Defined SH function (skipped while running under "command NAME ...").
691 if (!$_CMD_NO_FUNC && exists $_SH_FUNCTIONS{$cmd}) {
692 return _call_sh_function($class, $cmd, $rest, $opts_ref);
693 }
694  
695 # Unknown: try as external (runs via Perl system)
696 return _cmd_external($cmd, $rest);
697 }
698  
699 # ----------------------------------------------------------------
700 # Variable / arithmetic expansion
701 # ----------------------------------------------------------------
702 # ----------------------------------------------------------------
703 # Expansion-result protection
704 # ----------------------------------------------------------------
705 # BATsh expands a line first and removes quotes from it afterwards, so
706 # a backslash arriving as the RESULT of an expansion (a variable value,
707 # command-substitution output, or a tilde expansion) used to be re-read
708 # as a shell escape by the later quote-removal stage and silently
709 # deleted. On Windows that ate every path: with HOME set to
710 # C:\home\flower the line `cd ~` tried to enter C:homeflower, and
711 # `d="C:\Users\x"; cd $d` failed in the same way.
712 # POSIX quote removal applies to the source word only, never to what an
713 # expansion produced, so a backslash coming out of an expansion is
714 # stashed here behind a NUL-delimited sentinel (a NUL can never occur
715 # in shell source) and becomes a literal backslash again in
716 # _arr_dequote() -- or in _unprotect_lit(), for the few consumers that
717 # never dequote (external command lines, here-document bodies, the
718 # variable store).
719 # ----------------------------------------------------------------
720 sub _protect_lit {
721 my ($v) = @_;
722 return '' unless defined $v;
723 $v =~ s/\\/\x00BATSH_LB\x00/g;
724 return $v;
725 }
726  
727 sub _unprotect_lit {
728 my ($v) = @_;
729 return '' unless defined $v;
730 $v =~ s/\x00BATSH_LB\x00/\\/g;
731 return $v;
732 }
733  
734 sub _expand {
735 my ($class, $str) = @_;
736  
737 return '' unless defined $str;
738  
739 # Tilde expansion (v0.07) MUST run before variable / command
740 # substitution below: POSIX expands ~word from the literal source
741 # text only, once, at the start of a word (or right after the '='
742 # of a leading NAME= assignment). A ~ that only appears because a
743 # $VAR happened to hold a string starting with "~" must NOT be
744 # re-expanded -- doing tilde expansion after $VAR substitution
745 # cannot tell the two cases apart, so it must happen first here.
746 $str = _tilde_prepass($str);
747  
748 # Protect backslash escapes before any expansion. In POSIX shells the
749 # backslash inside double quotes keeps its special meaning only before
750 # $ ` " \ and newline, so "\$" is a literal dollar (NO expansion), "\`"
751 # is a literal backtick (NO command substitution) and "\\" is a literal
752 # backslash. Earlier releases performed the $-/`-substitutions globally
753 # with no escape awareness, so "\$_" expanded $_ to empty and left the
754 # stray backslash (giving e.g. perl -e "...uc(\)..." -> syntax error).
755 # We stash the escaped specials under NUL-delimited sentinels (a NUL can
756 # never occur in shell source) and restore them as literals at the end.
757 # Order matters: "\\" first so that "\\$" means backslash + expansion.
758 $str =~ s/\\\\/\x00BATSH_BS\x00/g; # \\ -> literal backslash
759 $str =~ s/\\\$/\x00BATSH_DL\x00/g; # \$ -> literal dollar (no expand)
760 $str =~ s/\\`/\x00BATSH_BT\x00/g; # \` -> literal backtick (no subst)
761  
762 # $(( arithmetic ))
763 $str =~ s/\$\(\(\s*(.*?)\s*\)\)/_eval_arith($1)/ge;
764  
765 # <(cmd) / >(cmd) process substitution (v0.07) -- MUST run before
766 # $(...) below, and before backtick substitution, so that <(...) is
767 # never mistaken for a stray "<" redirection operator by the later
768 # redirect-stripping stage.
769 $str = _replace_process_subst($class, $str);
770  
771 # $( command ) substitution
772 # Use _extract_cmd_subst to correctly handle nested () and quoted ) chars.
773 $str = _replace_cmd_subst($class, $str);
774  
775 # backtick command substitution: `cmd`
776 $str =~ s/`([^`]*)`/_protect_lit(_cmd_subst($class, $1))/ge;
777  
778 # ---- Array expansions (v0.06) ----------------------------------
779 # These MUST precede the scalar ${#VAR} / ${VAR} rules below so that a
780 # subscripted reference is never mis-parsed as a plain variable.
781  
782 # ${#NAME[@]} / ${#NAME[*]} -- number of set elements
783 $str =~ s/\$\{#([A-Za-z_][A-Za-z0-9_]*)\[[\@*]\]\}/
784 _arr_count($1)
785 /ge;
786  
787 # ${#NAME[SUB]} -- length of one element
788 $str =~ s/\$\{#([A-Za-z_][A-Za-z0-9_]*)\[([^\]]*)\]\}/
789 do {
790 my $v = _arr_get_element($1, _arr_expand_sub($class, $2));
791 defined $v ? length($v) : 0
792 }
793 /ge;
794  
795 # ${!NAME[@]} / ${!NAME[*]} -- list of indices / keys
796 $str =~ s/\$\{!([A-Za-z_][A-Za-z0-9_]*)\[[\@*]\]\}/
797 _protect_lit(join(' ', _arr_ordered_keys($1)))
798 /ge;
799  
800 # ${NAME[@]} / ${NAME[*]} -- all elements (space-joined word-split model)
801 $str =~ s/\$\{([A-Za-z_][A-Za-z0-9_]*)\[[\@*]\]\}/
802 _protect_lit(join(' ', _arr_values($1)))
803 /ge;
804  
805 # ${NAME[SUB]} -- single element
806 $str =~ s/\$\{([A-Za-z_][A-Za-z0-9_]*)\[([^\]]*)\]\}/
807 do {
808 my $v = _arr_get_element($1, _arr_expand_sub($class, $2));
809 defined $v ? _protect_lit($v) : ''
810 }
811 /ge;
812 # ----------------------------------------------------------------
813  
814 # ${#VAR} -- length of value (characters, not bytes, under DBCS guard)
815 $str =~ s/\$\{#([A-Za-z_][A-Za-z0-9_]*)\}/
816 do { my $v = BATsh::Env->get($1);
817 defined $v ? BATsh::MB::mb_length($v) : 0 }
818 /ge;
819  
820 # ${VAR%%pattern} -- remove longest suffix (MUST be before single %)
821 $str =~ s/\$\{([A-Za-z_][A-Za-z0-9_]*)%%([^}]*)\}/
822 do { my $v = BATsh::Env->get($1); $v = defined $v ? $v : ''; _protect_lit(_sh_remove_suffix($v, $2, 1)) }
823 /ge;
824  
825 # ${VAR%pattern} -- remove shortest suffix (single %, not %%)
826 $str =~ s/\$\{([A-Za-z_][A-Za-z0-9_]*)%(?!%)([^}]*)\}/
827 do { my $v = BATsh::Env->get($1); $v = defined $v ? $v : ''; _protect_lit(_sh_remove_suffix($v, $2, 0)) }
828 /ge;
829  
830 # ${VAR##pattern} -- remove longest prefix (MUST be before single #)
831 $str =~ s/\$\{([A-Za-z_][A-Za-z0-9_]*)##([^}]*)\}/
832 do { my $v = BATsh::Env->get($1); $v = defined $v ? $v : ''; _protect_lit(_sh_remove_prefix($v, $2, 1)) }
833 /ge;
834  
835 # ${VAR#pattern} -- remove shortest prefix (single #, not ##)
836 $str =~ s/\$\{([A-Za-z_][A-Za-z0-9_]*)#(?!#)([^}]*)\}/
837 do { my $v = BATsh::Env->get($1); $v = defined $v ? $v : ''; _protect_lit(_sh_remove_prefix($v, $2, 0)) }
838 /ge;
839  
840 # ${VAR//pat/rep} -- replace all occurrences (MUST be before single /)
841 $str =~ s/\$\{([A-Za-z_][A-Za-z0-9_]*)\/\/([^\/}]*)\/([^}]*)\}/
842 do { my $v = BATsh::Env->get($1); $v = defined $v ? $v : ''; _protect_lit(_sh_replace($v, $2, $3, 1)) }
843 /ge;
844  
845 # ${VAR/pat/rep} -- replace first occurrence (single /, not //)
846 $str =~ s/\$\{([A-Za-z_][A-Za-z0-9_]*)\/(?!\/)([^\/}]*)\/([^}]*)\}/
847 do { my $v = BATsh::Env->get($1); $v = defined $v ? $v : ''; _protect_lit(_sh_replace($v, $2, $3, 0)) }
848 /ge;
849  
850 # ${VAR^^} -- uppercase all
851 $str =~ s/\$\{([A-Za-z_][A-Za-z0-9_]*)\^\^\}/
852 do { my $v = BATsh::Env->get($1); defined $v ? _protect_lit(uc($v)) : '' }
853 /ge;
854  
855 # ${VAR^} -- uppercase first char
856 $str =~ s/\$\{([A-Za-z_][A-Za-z0-9_]*)\^\}/
857 do { my $v = BATsh::Env->get($1); $v = defined $v ? $v : ''; _protect_lit(ucfirst($v)) }
858 /ge;
859  
860 # ${VAR,,} -- lowercase all
861 $str =~ s/\$\{([A-Za-z_][A-Za-z0-9_]*),,\}/
862 do { my $v = BATsh::Env->get($1); defined $v ? _protect_lit(lc($v)) : '' }
863 /ge;
864  
865 # ${VAR,} -- lowercase first char
866 $str =~ s/\$\{([A-Za-z_][A-Za-z0-9_]*),\}/
867 do { my $v = BATsh::Env->get($1); $v = defined $v ? $v : ''; _protect_lit(lcfirst($v)) }
868 /ge;
869  
870 # ${VAR:offset:length} and ${VAR:offset}
871 $str =~ s/\$\{([A-Za-z_][A-Za-z0-9_]*):(-?\d+):(\d+)\}/
872 do {
873 my $v = BATsh::Env->get($1); $v = defined $v ? $v : '';
874 _protect_lit(BATsh::MB::mb_substr($v, int($2), int($3)))
875 }
876 /ge;
877 $str =~ s/\$\{([A-Za-z_][A-Za-z0-9_]*):(-?\d+)\}/
878 do {
879 my $v = BATsh::Env->get($1); $v = defined $v ? $v : '';
880 _protect_lit(BATsh::MB::mb_substr($v, int($2)))
881 }
882 /ge;
883  
884 # ${VAR:-default} ${VAR:=default} ${VAR:+alt}
885 $str =~ s/\$\{([A-Za-z_][A-Za-z0-9_]*):-(.*?)\}/
886 do { my $v = BATsh::Env->get($1); (defined $v && $v ne '') ? _protect_lit($v) : $2 }
887 /ge;
888 $str =~ s/\$\{([A-Za-z_][A-Za-z0-9_]*):=(.*?)\}/
889 do {
890 my $v = BATsh::Env->get($1);
891 if (!defined $v || $v eq '') { BATsh::Env->set($1, $2); $v = $2 }
892 else { $v = _protect_lit($v) }
893 $v
894 }
895 /ge;
896 $str =~ s/\$\{([A-Za-z_][A-Za-z0-9_]*):\+([^}]*)\}/
897 do { my $v = BATsh::Env->get($1); (defined $v && $v ne '') ? $2 : '' }
898 /ge;
899  
900 # ${VAR} -- plain expansion (array name yields element 0)
901 $str =~ s/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/
902 do {
903 my $n = $1;
904 if (_arr_exists($n)) {
905 my $v = _arr_get_element($n, 0); defined $v ? _protect_lit($v) : ''
906 }
907 else {
908 my $v = BATsh::Env->get($n);
909 _nounset_hit($n) if !defined $v;
910 defined $v ? _protect_lit($v) : ''
911 }
912 }
913 /ge;
914  
915 # $? last status
916 $str =~ s/\$\?/$LAST_STATUS/g;
917  
918 # $$ PID
919 $str =~ s/\$\$/$$/g;
920  
921 # $! PID of the most recent background job (empty before any)
922 $str =~ s/\$\!/$_LAST_BG_PID/g;
923  
924  
925 # $0 script name
926 $str =~ s/\$0/do { my $v=BATsh::Env->get('%0'); defined $v ? _protect_lit($v) : '' }/ge;
927  
928 # $1..$9 positional parameters
929 $str =~ s/\$([1-9])/
930 do {
931 my $n = $1;
932 my $v = BATsh::Env->get("%$n");
933 $v = BATsh::Env->get("BATSH_ARG$n") unless defined $v && $v ne '';
934 defined $v ? _protect_lit($v) : ''
935 }
936 /ge;
937  
938 # $@ and $* all positional parameters (both join with a space here).
939 # Historically only $@ was substituted; $* fell through unexpanded and
940 # printed literally. Both now expand to the space-joined parameter
941 # list held in %*.
942 $str =~ s/\$\@/do { my $v=BATsh::Env->get('%*'); defined $v ? _protect_lit($v) : '' }/ge;
943 $str =~ s/\$\*/do { my $v=BATsh::Env->get('%*'); defined $v ? _protect_lit($v) : '' }/ge;
944  
945 # $# number of positional parameters
946 $str =~ s/\$#/
947 do {
948 my $c = 0;
949 for my $nn (1..9) {
950 my $vv = BATsh::Env->get("%$nn");
951 $vv = BATsh::Env->get("BATSH_ARG$nn") unless defined $vv && $vv ne '';
952 last unless defined $vv && $vv ne '';
953 $c = $nn;
954 }
955 $c
956 }
957 /ge;
958  
959 # $VAR (array name yields element 0)
960 $str =~ s/\$([A-Za-z_][A-Za-z0-9_]*)/
961 do {
962 my $n = $1;
963 if (_arr_exists($n)) {
964 my $v = _arr_get_element($n, 0); defined $v ? _protect_lit($v) : ''
965 }
966 else {
967 my $v = BATsh::Env->get($n);
968 _nounset_hit($n) if !defined $v;
969 defined $v ? _protect_lit($v) : ''
970 }
971 }
972 /ge;
973  
974 # Restore the escaped specials as literal characters (reverse order of
975 # protection is not required, the sentinels are disjoint).
976 $str =~ s/\x00BATSH_DL\x00/\$/g;
977 $str =~ s/\x00BATSH_BT\x00/`/g;
978 $str =~ s/\x00BATSH_BS\x00/\\/g;
979  
980 return $str;
981 }
982  
983 # ----------------------------------------------------------------
984 # Arithmetic evaluator
985 # ----------------------------------------------------------------
986 use vars qw(@_A_TOK $_A_POS $_A_ERR);
987  
988 sub _eval_arith {
989 my ($expr) = @_;
990 # Full shell-arithmetic evaluator (bash semantics, Perl 5.005_03 safe):
991 # , = += -= *= /= %= <<= >>= &= ^= |= ?: || && | ^ & == != < <= > >=
992 # << >> + - * / % ** (right assoc) unary ! ~ + - prefix/postfix ++ --
993 # Comparisons and logical operators yield 1/0; / and % truncate toward
994 # zero; assignments and ++/-- on a bare NAME write back to the variable
995 # store. $N and $NAME are resolved to their numeric values while
996 # tokenizing; a bare NAME stays assignable. Numbers may be decimal,
997 # hex (0x..), or octal (0..). On any syntax error or division by zero
998 # a warning is printed and 0 is returned (matching the old behaviour
999 # of returning 0 on an unsupported expression).
1000 local @_A_TOK = _arith_tokenize(defined $expr ? $expr : '');
1001 local $_A_POS = 0;
1002 local $_A_ERR = 0;
1003 my ($v) = _a_comma();
1004 $_A_ERR = 1 if !$_A_ERR && $_A_POS < scalar(@_A_TOK); # trailing junk
1005 if ($_A_ERR) {
1006 warn "sh: arithmetic: syntax error or division by zero: $expr\n";
1007 return 0;
1008 }
1009 return int($v);
1010 }
1011  
1012 # Tokenize into [TYPE, VALUE] pairs: TYPE 'n' number, 'v' name, 'o' operator.
1013 sub _arith_tokenize {
1014 my ($s) = @_;
1015 my @tok = ();
1016 my $i = 0;
1017 my $n = length($s);
1018 while ($i < $n) {
1019 my $c = substr($s, $i, 1);
1020 if ($c =~ /\s/) { $i++; next }
1021 # $N positional / $NAME -- resolve to a numeric value now
1022 if ($c eq '$') {
1023 if (substr($s, $i+1, 1) =~ /\A[1-9]\z/) {
1024 push @tok, ['n', _arith_pos(substr($s, $i+1, 1))];
1025 $i += 2; next;
1026 }
1027 if (substr($s, $i+1) =~ /\A([A-Za-z_][A-Za-z0-9_]*)/) {
1028 push @tok, ['n', _arith_var($1)];
1029 $i += 1 + length($1); next;
1030 }
1031 return (['o', '?ERR?']); # lone $: force a syntax error
1032 }
1033 # Numbers: hex 0x.., octal 0.., decimal
1034 if ($c =~ /\d/) {
1035 if ($c eq '0' && substr($s, $i+1, 1) =~ /\A[xX]\z/
1036 && substr($s, $i+2) =~ /\A([0-9A-Fa-f]+)/) {
1037 push @tok, ['n', hex($1)];
1038 $i += 2 + length($1); next;
1039 }
1040 substr($s, $i) =~ /\A(\d+)/;
1041 my $num = $1;
1042 if ($num =~ /\A0[0-7]+\z/) { push @tok, ['n', oct($num)] }
1043 else { push @tok, ['n', int($num)] }
1044 $i += length($num); next;
1045 }
1046 # Bare NAME (assignable lvalue)
1047 if ($c =~ /[A-Za-z_]/) {
1048 substr($s, $i) =~ /\A([A-Za-z_][A-Za-z0-9_]*)/;
1049 push @tok, ['v', $1];
1050 $i += length($1); next;
1051 }
1052 # Operators: longest match first
1053 my $three = substr($s, $i, 3);
1054 if ($three eq '<<=' || $three eq '>>=') {
1055 push @tok, ['o', $three]; $i += 3; next;
1056 }
1057 my $two = substr($s, $i, 2);
1058 if ($two =~ /\A(?:\*\*|<<|>>|<=|>=|==|!=|&&|\|\||\+=|-=|\*=|\/=|%=|&=|\^=|\|=|\+\+|--)\z/) {
1059 push @tok, ['o', $two]; $i += 2; next;
1060 }
1061 if ($c =~ /\A[-+*\/%()<>=!&|^~?:,]\z/) {
1062 push @tok, ['o', $c]; $i++; next;
1063 }
1064 return (['o', '?ERR?']); # unknown character: force a syntax error
1065 }
1066 return @tok;
1067 }
1068  
1069 sub _a_peek { return $_A_POS < @_A_TOK ? $_A_TOK[$_A_POS] : undef }
1070 sub _a_isop {
1071 my ($op) = @_;
1072 my $t = _a_peek();
1073 return defined $t && $t->[0] eq 'o' && $t->[1] eq $op;
1074 }
1075 sub _a_next { return $_A_TOK[$_A_POS++] }
1076  
1077 # Each _a_* returns (value, lvalue_name_or_undef).
1078  
1079 sub _a_comma {
1080 my ($v, $lv) = _a_assign();
1081 while (_a_isop(',')) {
1082 _a_next();
1083 ($v, $lv) = _a_assign();
1084 }
1085 return ($v, undef);
1086 }
1087  
1088 sub _a_assign {
1089 # Lookahead: NAME followed by an assignment operator
1090 my $t = _a_peek();
1091 if (defined $t && $t->[0] eq 'v' && $_A_POS + 1 < @_A_TOK) {
1092 my $op = $_A_TOK[$_A_POS + 1];
1093 if ($op->[0] eq 'o' && $op->[1] =~ /\A(?:=|\+=|-=|\*=|\/=|%=|<<=|>>=|&=|\^=|\|=)\z/) {
1094 my $name = $t->[1];
1095 _a_next(); _a_next();
1096 my ($rhs) = _a_assign();
1097 my $val;
1098 if ($op->[1] eq '=') { $val = $rhs }
1099 else {
1100 my $cur = _arith_var($name);
1101 my $o = $op->[1];
1102 if ($o eq '+=') { $val = $cur + $rhs }
1103 elsif ($o eq '-=') { $val = $cur - $rhs }
1104 elsif ($o eq '*=') { $val = $cur * $rhs }
1105 elsif ($o eq '/=') { if ($rhs == 0) { $_A_ERR = 1; return (0, undef) }
1106 $val = int($cur / $rhs) }
1107 elsif ($o eq '%=') { if ($rhs == 0) { $_A_ERR = 1; return (0, undef) }
1108 $val = $cur % $rhs }
1109 elsif ($o eq '<<=') { $val = $cur << $rhs }
1110 elsif ($o eq '>>=') { $val = $cur >> $rhs }
1111 elsif ($o eq '&=') { $val = $cur & $rhs }
1112 elsif ($o eq '^=') { $val = $cur ^ $rhs }
1113 else { $val = $cur | $rhs }
1114 }
1115 $val = int($val);
1116 BATsh::Env->set($name, $val);
1117 return ($val, undef);
1118 }
1119 }
1120 return _a_ternary();
1121 }
1122  
1123 sub _a_ternary {
1124 my ($c) = _a_lor();
1125 if (_a_isop('?')) {
1126 _a_next();
1127 my ($tv) = _a_assign();
1128 if (!_a_isop(':')) { $_A_ERR = 1; return (0, undef) }
1129 _a_next();
1130 my ($fv) = _a_ternary();
1131 return (($c != 0) ? $tv : $fv, undef);
1132 }
1133 return ($c, undef);
1134 }
1135  
1136 sub _a_lor {
1137 my ($v) = _a_land();
1138 while (_a_isop('||')) {
1139 _a_next();
1140 my ($r) = _a_land();
1141 $v = (($v != 0) || ($r != 0)) ? 1 : 0;
1142 }
1143 return ($v, undef);
1144 }
1145  
1146 sub _a_land {
1147 my ($v) = _a_bor();
1148 while (_a_isop('&&')) {
1149 _a_next();
1150 my ($r) = _a_bor();
1151 $v = (($v != 0) && ($r != 0)) ? 1 : 0;
1152 }
1153 return ($v, undef);
1154 }
1155  
1156 sub _a_bor {
1157 my ($v) = _a_bxor();
1158 while (_a_isop('|')) {
1159 _a_next();
1160 my ($r) = _a_bxor();
1161 $v = $v | $r;
1162 }
1163 return ($v, undef);
1164 }
1165  
1166 sub _a_bxor {
1167 my ($v) = _a_band();
1168 while (_a_isop('^')) {
1169 _a_next();
1170 my ($r) = _a_band();
1171 $v = $v ^ $r;
1172 }
1173 return ($v, undef);
1174 }
1175  
1176 sub _a_band {
1177 my ($v) = _a_eqne();
1178 while (_a_isop('&')) {
1179 _a_next();
1180 my ($r) = _a_eqne();
1181 $v = $v & $r;
1182 }
1183 return ($v, undef);
1184 }
1185  
1186 sub _a_eqne {
1187 my ($v) = _a_rel();
1188 while (_a_isop('==') || _a_isop('!=')) {
1189 my $op = _a_next()->[1];
1190 my ($r) = _a_rel();
1191 $v = ($op eq '==') ? (($v == $r) ? 1 : 0) : (($v != $r) ? 1 : 0);
1192 }
1193 return ($v, undef);
1194 }
1195  
1196 sub _a_rel {
1197 my ($v) = _a_shiftop();
1198 while (_a_isop('<') || _a_isop('<=') || _a_isop('>') || _a_isop('>=')) {
1199 my $op = _a_next()->[1];
1200 my ($r) = _a_shiftop();
1201 if ($op eq '<') { $v = ($v < $r) ? 1 : 0 }
1202 elsif ($op eq '<=') { $v = ($v <= $r) ? 1 : 0 }
1203 elsif ($op eq '>') { $v = ($v > $r) ? 1 : 0 }
1204 else { $v = ($v >= $r) ? 1 : 0 }
1205 }
1206 return ($v, undef);
1207 }
1208  
1209 sub _a_shiftop {
1210 my ($v) = _a_add();
1211 while (_a_isop('<<') || _a_isop('>>')) {
1212 my $op = _a_next()->[1];
1213 my ($r) = _a_add();
1214 $v = ($op eq '<<') ? ($v << $r) : ($v >> $r);
1215 }
1216 return ($v, undef);
1217 }
1218  
1219 sub _a_add {
1220 my ($v) = _a_mul();
1221 while (_a_isop('+') || _a_isop('-')) {
1222 my $op = _a_next()->[1];
1223 my ($r) = _a_mul();
1224 $v = ($op eq '+') ? ($v + $r) : ($v - $r);
1225 }
1226 return ($v, undef);
1227 }
1228  
1229 sub _a_mul {
1230 my ($v) = _a_pow();
1231 while (_a_isop('*') || _a_isop('/') || _a_isop('%')) {
1232 my $op = _a_next()->[1];
1233 my ($r) = _a_pow();
1234 if ($op eq '*') { $v = $v * $r }
1235 else {
1236 if ($r == 0) { $_A_ERR = 1; return (0, undef) }
1237 # bash / and % truncate toward zero
1238 if ($op eq '/') {
1239 my $q = abs(int($v)) - (abs(int($v)) % abs(int($r)));
1240 $q /= abs(int($r));
1241 $q = -$q if (($v < 0) ne ($r < 0)) && $q != 0;
1242 $v = $q;
1243 }
1244 else {
1245 my $m = abs(int($v)) % abs(int($r));
1246 $m = -$m if $v < 0;
1247 $v = $m;
1248 }
1249 }
1250 }
1251 return ($v, undef);
1252 }
1253  
1254 sub _a_pow {
1255 my ($v, $lv) = _a_unary();
1256 if (_a_isop('**')) {
1257 _a_next();
1258 my ($r) = _a_pow(); # right associative
1259 return (int($v ** $r), undef);
1260 }
1261 return ($v, $lv);
1262 }
1263  
1264 sub _a_unary {
1265 if (_a_isop('!')) { _a_next(); my ($v) = _a_unary(); return (($v == 0) ? 1 : 0, undef) }
1266 if (_a_isop('~')) { _a_next(); my ($v) = _a_unary(); return (-int($v) - 1, undef) }
1267 if (_a_isop('+')) { _a_next(); my ($v) = _a_unary(); return (+$v, undef) }
1268 if (_a_isop('-')) { _a_next(); my ($v) = _a_unary(); return (-$v, undef) }
1269 # Prefix ++NAME / --NAME
1270 if (_a_isop('++') || _a_isop('--')) {
1271 my $op = _a_next()->[1];
1272 my $t = _a_peek();
1273 if (!defined $t || $t->[0] ne 'v') { $_A_ERR = 1; return (0, undef) }
1274 _a_next();
1275 my $val = _arith_var($t->[1]) + (($op eq '++') ? 1 : -1);
1276 BATsh::Env->set($t->[1], $val);
1277 return ($val, undef);
1278 }
1279 return _a_postfix();
1280 }
1281  
1282 sub _a_postfix {
1283 my ($v, $lv) = _a_primary();
1284 if (defined $lv && (_a_isop('++') || _a_isop('--'))) {
1285 my $op = _a_next()->[1];
1286 BATsh::Env->set($lv, $v + (($op eq '++') ? 1 : -1));
1287 return ($v, undef); # postfix returns the OLD value
1288 }
1289 return ($v, $lv);
1290 }
1291  
1292 sub _a_primary {
1293 my $t = _a_peek();
1294 if (!defined $t) { $_A_ERR = 1; return (0, undef) }
1295 if ($t->[0] eq 'o' && $t->[1] eq '(') {
1296 _a_next();
1297 my ($v) = _a_comma();
1298 if (!_a_isop(')')) { $_A_ERR = 1; return (0, undef) }
1299 _a_next();
1300 return ($v, undef);
1301 }
1302 if ($t->[0] eq 'n') { _a_next(); return ($t->[1], undef) }
1303 if ($t->[0] eq 'v') { _a_next(); return (_arith_var($t->[1]), $t->[1]) }
1304 $_A_ERR = 1;
1305 return (0, undef);
1306 }
1307  
1308 sub _arith_pos {
1309 my ($n) = @_;
1310 my $v = BATsh::Env->get("%$n");
1311 $v = BATsh::Env->get("BATSH_ARG$n") unless defined $v && $v ne '';
1312 return (defined $v && $v =~ /\A-?\d+\z/) ? $v : 0;
1313 }
1314  
1315 sub _arith_var {
1316 my ($name) = @_;
1317 my $v = BATsh::Env->get($name);
1318 return (defined $v && $v =~ /\A-?\d+\z/) ? $v : 0;
1319 }
1320  
1321 # ----------------------------------------------------------------
1322 # Command substitution $( cmd )
1323 # ----------------------------------------------------------------
1324 # _replace_cmd_subst: replace all $(...) in $str with their output.
1325 # Unlike a simple [^)]* regex, this function tracks nesting depth
1326 # and quoted strings so that $(cmd | perl -e "...)" works correctly.
1327 # ----------------------------------------------------------------
1328 sub _replace_cmd_subst {
1329 my ($class, $str) = @_;
1330 return '' unless defined $str;
1331  
1332 my $result = '';
1333 my @chars = split //, $str;
1334 my $n = scalar @chars;
1335 my $i = 0;
1336  
1337 while ($i < $n) {
1338 my $ch = $chars[$i];
1339  
1340 # $( ... ) -- find matching close paren respecting nesting and quotes
1341 if ($ch eq '$' && $i+1 < $n && $chars[$i+1] eq '(') {
1342 $i += 2; # skip $(
1343 my $depth = 1;
1344 my $body = '';
1345 my $in_sq = 0;
1346 my $in_dq = 0;
1347  
1348 while ($i < $n && $depth > 0) {
1349 my $c = $chars[$i];
1350  
1351 if ($in_sq) {
1352 if ($c eq "'") { $in_sq = 0 }
1353 $body .= $c; $i++; next;
1354 }
1355 if ($c eq "'" && !$in_dq) {
1356 $in_sq = 1; $body .= $c; $i++; next;
1357 }
1358 if ($c eq '"' && !$in_sq) {
1359 $in_dq = !$in_dq; $body .= $c; $i++; next;
1360 }
1361 if ($in_dq) {
1362 if ($c eq '\\') {
1363 $body .= $c; $i++;
1364 $body .= $chars[$i] if $i < $n; $i++; next;
1365 }
1366 $body .= $c; $i++; next;
1367 }
1368 if ($c eq '\\') {
1369 $body .= $c; $i++;
1370 $body .= $chars[$i] if $i < $n; $i++; next;
1371 }
1372 if ($c eq '(') { $depth++; $body .= $c; $i++; next }
1373 if ($c eq ')') {
1374 $depth--;
1375 if ($depth == 0) { $i++; last } # closing )
1376 $body .= $c; $i++; next;
1377 }
1378 $body .= $c; $i++;
1379 }
1380  
1381 $result .= _protect_lit(_cmd_subst($class, $body));
1382 next;
1383 }
1384  
1385 $result .= $ch; $i++;
1386 }
1387  
1388 return $result;
1389 }
1390  
1391 # ----------------------------------------------------------------
1392 sub _cmd_subst {
1393 my ($class, $cmd_str) = @_;
1394 # Capture stdout via temporary file (Perl 5.005_03 compatible).
1395 # We use _run_lines so that all BATsh::SH builtins, functions,
1396 # and pipelines work recursively inside $(...) and `...`.
1397 # Tag the capture file with the active nesting depth so a nested
1398 # $( ... $( ... ) ) gets a distinct file per level (the inner level
1399 # must not truncate/unlink the file the outer level captures into).
1400 local $_SUBST_DEPTH = $_SUBST_DEPTH + 1;
1401 local *_SUBST_SAVOUT;
1402 open(_SUBST_SAVOUT, '>&STDOUT') or return '';
1403 local *_SUBST_CAPFH;
1404 my $tmpfile = _subst_tempfile();
1405 if (!defined $tmpfile) {
1406 open(STDOUT, '>&_SUBST_SAVOUT'); close(_SUBST_SAVOUT); return '';
1407 }
1408 open(STDOUT, '>&_SUBST_CAPFH')
1409 or do {
1410 close(_SUBST_CAPFH); unlink $tmpfile;
1411 open(STDOUT, '>&_SUBST_SAVOUT'); close(_SUBST_SAVOUT); return '';
1412 };
1413 close(_SUBST_CAPFH);
1414 eval {
1415 # Use _run_lines for full recursive BATsh::SH execution.
1416 # $cmd_str may contain pipes, builtins, functions, etc.
1417 my @sub_lines = split /\n/, $cmd_str;
1418 _run_lines($class, \@sub_lines, {});
1419 };
1420 open(STDOUT, '>&_SUBST_SAVOUT');
1421 close(_SUBST_SAVOUT);
1422 my $output = '';
1423 local *_SUBST_READFH;
1424 if (open(_SUBST_READFH, "< $tmpfile")) {
1425 local $/;
1426 $output = <_SUBST_READFH>;
1427 close(_SUBST_READFH);
1428 }
1429 unlink $tmpfile;
1430 @_SUBST_TMPFILES = grep { $_ ne $tmpfile } @_SUBST_TMPFILES;
1431 $output = '' unless defined $output;
1432 $output =~ s/\n+\z//; # strip trailing newlines (like shell)
1433 return BATsh::MB::enc($output);
1434 }
1435  
1436 # _subst_tempfile: create a unique, empty temp file (O_CREAT|O_EXCL to
1437 # avoid symlink races -- mirrors _bg_tempfile / _hd_tempfile) for capturing
1438 # one command-substitution's stdout output, and open it as the package
1439 # bareword filehandle _SUBST_CAPFH. Returns the path, or undef on failure.
1440 sub _subst_tempfile {
1441 my $dir = File::Spec->tmpdir();
1442 $dir = '.' if !(-d $dir && -w $dir);
1443  
1444 my $attempt = 0;
1445 while ($attempt < 1000) {
1446 $_SUBST_SEQ++;
1447 $attempt++;
1448 my $path = File::Spec->catfile($dir,
1449 'batsh_cap_' . $$ . '_' . $_SUBST_DEPTH . '_' . $_SUBST_SEQ . '.tmp');
1450 if (sysopen(_SUBST_CAPFH, $path, O_WRONLY | O_CREAT | O_EXCL, 0600)) {
1451 push @_SUBST_TMPFILES, $path;
1452 return $path;
1453 }
1454 # EEXIST or transient error: retry with next sequence number
1455 }
1456 return undef;
1457 }
1458  
1459 # ----------------------------------------------------------------
1460 # Process substitution (v0.07): <(cmd) and >(cmd).
1461 #
1462 # This interpreter never forks (see the pipeline / background-job notes
1463 # elsewhere in this file), so neither form uses a real named pipe.
1464 # Instead:
1465 #
1466 # <(cmd) cmd's stdout is captured into a temp file (exactly like
1467 # $(cmd), but the file is kept instead of being read back
1468 # into a scalar) and <(cmd) is replaced by that file's path.
1469 # This covers the common case of feeding a whole command's
1470 # output to something that wants a filename, e.g.
1471 # "diff <(sort a) <(sort b)".
1472 #
1473 # >(cmd) an empty temp file is created and >(cmd) is replaced by its
1474 # path immediately; cmd itself is deferred and run with that
1475 # file as its stdin only after the current simple command
1476 # finishes (see the _exec_line wrapper), e.g.
1477 # "generate | tee >(gzip > out.gz)". Because cmd runs after
1478 # (not concurrently with) the writer, this is a best-effort
1479 # approximation of real, streaming >(...) and does not suit
1480 # writers that expect the reader to keep up in real time.
1481 #
1482 # Both temp files are removed by the _exec_line wrapper once the current
1483 # simple command (and, for >(cmd), its deferred job) has finished; a
1484 # process substitution used INSIDE another command substitution / loop
1485 # condition is cleaned up at that inner level, not held open for the
1486 # rest of the script.
1487 # ----------------------------------------------------------------
1488 sub _replace_process_subst {
1489 my ($class, $str) = @_;
1490 return $str unless defined $str && $str =~ /[<>]\(/;
1491  
1492 my $result = '';
1493 my @chars = split //, $str;
1494 my $n = scalar @chars;
1495 my $i = 0;
1496 my $in_sq = 0;
1497 my $in_dq = 0;
1498  
1499 while ($i < $n) {
1500 my $ch = $chars[$i];
1501  
1502 if ($in_sq) {
1503 if ($ch eq "'") { $in_sq = 0 }
1504 $result .= $ch; $i++; next;
1505 }
1506 if ($ch eq "'" && !$in_dq) { $in_sq = 1; $result .= $ch; $i++; next }
1507 if ($ch eq '"' && !$in_sq) { $in_dq = !$in_dq; $result .= $ch; $i++; next }
1508 if (!$in_dq && $ch eq '\\') {
1509 $result .= $ch; $i++;
1510 $result .= $chars[$i] if $i < $n; $i++; next;
1511 }
1512  
1513 if (!$in_sq && !$in_dq && ($ch eq '<' || $ch eq '>')
1514 && $i+1 < $n && $chars[$i+1] eq '(') {
1515 my $dir = $ch;
1516 my $depth = 1;
1517 my $j = $i + 2;
1518 my $body = '';
1519 while ($j < $n && $depth > 0) {
1520 my $c = $chars[$j];
1521 if ($c eq '(') { $depth++; $body .= $c; $j++ }
1522 elsif ($c eq ')') { $depth--; $j++; $body .= $c if $depth > 0 }
1523 else { $body .= $c; $j++ }
1524 }
1525 if ($depth != 0) { $result .= $ch; $i++; next } # unterminated: literal '<'/'>'
1526  
1527 if ($dir eq '<') {
1528 # Quote the generated path: it is a literal filename that
1529 # must survive the dequoting applied later to redirection
1530 # targets and command words -- otherwise a Windows temp
1531 # path (C:\...\batsh_ps.tmp) would lose its backslashes,
1532 # or a space in the temp dir would split the word.
1533 $result .= '"' . _procsub_capture($class, $body) . '"';
1534 }
1535 else {
1536 my $tmp = _procsub_tempfile();
1537 if (defined $tmp) {
1538 close(_PROCSUB_CAPFH);
1539 push @_PROCSUB_DEFERRED, [$tmp, $body];
1540 $result .= '"' . $tmp . '"';
1541 }
1542 }
1543 $i = $j; next;
1544 }
1545  
1546 $result .= $ch; $i++;
1547 }
1548  
1549 return $result;
1550 }
1551  
1552 # _procsub_capture: run $cmd_str now, capturing its stdout into a fresh
1553 # temp file kept on disk, and return the file's path. Mirrors
1554 # _cmd_subst() but keeps the file instead of reading it back.
1555 sub _procsub_capture {
1556 my ($class, $cmd_str) = @_;
1557 local *_PROCSUB_SAVOUT;
1558 open(_PROCSUB_SAVOUT, '>&STDOUT') or return '';
1559 my $tmpfile = _procsub_tempfile();
1560 if (!defined $tmpfile) {
1561 open(STDOUT, '>&_PROCSUB_SAVOUT'); close(_PROCSUB_SAVOUT); return '';
1562 }
1563 open(STDOUT, '>&_PROCSUB_CAPFH')
1564 or do {
1565 close(_PROCSUB_CAPFH); unlink $tmpfile;
1566 @_PROCSUB_TMPFILES = grep { $_ ne $tmpfile } @_PROCSUB_TMPFILES;
1567 open(STDOUT, '>&_PROCSUB_SAVOUT'); close(_PROCSUB_SAVOUT); return '';
1568 };
1569 close(_PROCSUB_CAPFH);
1570 eval {
1571 my @sub_lines = split /\n/, $cmd_str;
1572 _run_lines($class, \@sub_lines, {});
1573 };
1574 open(STDOUT, '>&_PROCSUB_SAVOUT');
1575 close(_PROCSUB_SAVOUT);
1576 return $tmpfile;
1577 }
1578  
1579 # _procsub_tempfile: create a unique, empty temp file (O_CREAT|O_EXCL to
1580 # avoid symlink races, mirroring _subst_tempfile()) and open it as the
1581 # package bareword filehandle _PROCSUB_CAPFH. Returns the path, or
1582 # undef on failure. The path is tracked in @_PROCSUB_TMPFILES for the
1583 # _exec_line wrapper (normal cleanup) and the END-block failsafe.
1584 sub _procsub_tempfile {
1585 my $dir = File::Spec->tmpdir();
1586 $dir = '.' if !(-d $dir && -w $dir);
1587  
1588 my $attempt = 0;
1589 while ($attempt < 1000) {
1590 $_PROCSUB_SEQ++;
1591 $attempt++;
1592 my $path = File::Spec->catfile($dir,
1593 'batsh_ps_' . $$ . '_' . $_PROCSUB_SEQ . '.tmp');
1594 if (sysopen(_PROCSUB_CAPFH, $path, O_WRONLY | O_CREAT | O_EXCL, 0600)) {
1595 push @_PROCSUB_TMPFILES, $path;
1596 return $path;
1597 }
1598 # EEXIST or transient error: retry with next sequence number
1599 }
1600 return undef;
1601 }
1602  
1603 # ----------------------------------------------------------------
1604 # export
1605 # ----------------------------------------------------------------
1606 sub _cmd_export {
1607 my ($rest) = @_;
1608 $rest =~ s/\A\s+//;
1609 # export -p: print all
1610 if ($rest =~ /\A-p\s*\z/) {
1611 for my $k (sort keys %BATsh::Env::STORE) {
1612 my $v = $BATsh::Env::STORE{$k};
1613 $v =~ s/'/'\\''/g;
1614 print "export $k='$v'\n";
1615 }
1616 return 0;
1617 }
1618 # export VAR=value or export VAR. The value is split on UNQUOTED
1619 # whitespace and dequoted exactly like an ordinary assignment, so
1620 # `export V='C:\x'` exports C:\x rather than the quote characters
1621 # themselves, and `export V="a b"` keeps its embedded space.
1622 for my $item (_arr_split_words($rest)) {
1623 if ($item =~ /\A([A-Za-z_][A-Za-z0-9_]*)=(.*)\z/s) {
1624 _sh_store_scalar($1, _arr_dequote($2));
1625 }
1626 elsif ($item =~ /\A([A-Za-z_][A-Za-z0-9_]*)\z/) {
1627 # export existing variable (already in store; no-op)
1628 }
1629 }
1630 $LAST_STATUS = 0;
1631 return 0;
1632 }
1633  
1634 # ----------------------------------------------------------------
1635 # unset
1636 # ----------------------------------------------------------------
1637 sub _cmd_unset {
1638 my ($rest) = @_;
1639 my $status = 0;
1640 for my $var (split /\s+/, $rest) {
1641 $var =~ s/\A\s+//; $var =~ s/\s+\z//;
1642 next if $var eq '';
1643 # A readonly variable / element cannot be unset (bash: status 1).
1644 if ($_SH_READONLY{ uc($var) }) {
1645 print STDERR "sh: unset: $var: cannot unset: readonly variable\n";
1646 $status = 1;
1647 next;
1648 }
1649 # unset NAME[SUB] -- remove a single array element
1650 if ($var =~ /\A([A-Za-z_][A-Za-z0-9_]*)\[([^\]]*)\]\z/) {
1651 my ($name, $sub) = ($1, $2);
1652 my $k = _arr_name($name);
1653 if (exists $_SH_ARRAY{$k}) {
1654 if ((defined $_SH_ARRAY_TYPE{$k} && $_SH_ARRAY_TYPE{$k} eq 'assoc')) {
1655 delete $_SH_ARRAY{$k}{$sub};
1656 }
1657 else {
1658 delete $_SH_ARRAY{$k}{ _arr_index($sub) };
1659 }
1660 }
1661 next;
1662 }
1663 # unset NAME -- remove a whole array (and any scalar of the same name)
1664 my $k = _arr_name($var);
1665 if (exists $_SH_ARRAY{$k}) {
1666 delete $_SH_ARRAY{$k};
1667 delete $_SH_ARRAY_TYPE{$k};
1668 }
1669 BATsh::Env->unset($var);
1670 }
1671 $LAST_STATUS = $status;
1672 return $status;
1673 }
1674  
1675 # ----------------------------------------------------------------
1676 # echo
1677 # ----------------------------------------------------------------
1678 sub _cmd_echo {
1679 my ($rest) = @_;
1680 $rest =~ s/\A\s+//;
1681 my $no_newline = 0;
1682 if ($rest =~ s/\A-n\s*//) { $no_newline = 1 }
1683 # -e: enable escape sequences
1684 my $escape = 0;
1685 if ($rest =~ s/\A-e\s*//) { $escape = 1 }
1686 if ($escape) {
1687 $rest =~ s/\\n/\n/g;
1688 $rest =~ s/\\t/\t/g;
1689 $rest =~ s/\\r/\r/g;
1690 $rest =~ s/\\\\/\\/g;
1691 # The same sequences arriving from an expansion (v='a\tb';
1692 # echo -e $v) still carry the protection sentinel in place of
1693 # their backslash, and are interpreted here as well; a protected
1694 # backslash that does not start a known escape stays protected,
1695 # so a Windows path keeps its separators.
1696 $rest =~ s/\x00BATSH_LB\x00n/\n/g;
1697 $rest =~ s/\x00BATSH_LB\x00t/\t/g;
1698 $rest =~ s/\x00BATSH_LB\x00r/\r/g;
1699 $rest =~ s/\x00BATSH_LB\x00\x00BATSH_LB\x00/\x00BATSH_LB\x00/g;
1700 }
1701 # Remove shell quoting structurally so that quotes anywhere in the
1702 # argument list are dropped (e.g. echo "${arr[@]}" tail), not only when
1703 # the whole string is wrapped in one pair of quotes.
1704 $rest = _arr_dequote($rest);
1705 $rest = BATsh::MB::dec($rest);
1706 if ($no_newline) { print $rest }
1707 else { print "$rest\n" }
1708 $LAST_STATUS = 0;
1709 return 0;
1710 }
1711  
1712 # ----------------------------------------------------------------
1713 # printf
1714 # ----------------------------------------------------------------
1715 # A faithful pure-Perl printf: POSIX/bash format-string escapes, the full
1716 # conversion set (%d %i %o %u %x %X %e %E %f %g %G %c %s %b %q %%), field
1717 # width / precision including the dynamic "*" form, argument RECYCLING (the
1718 # format is reused until the arguments are exhausted), the "%b" conversion
1719 # (backslash escapes interpreted in the argument, with "\c" ending output),
1720 # the "%q" conversion (shell-reusable quoting), and the "-v VAR" option
1721 # (store the result in a shell variable instead of printing). Perl 5.005_03
1722 # safe: no lexical filehandles, no 3-argument open, no post-5.005 sprintf
1723 # conversions (%a is deliberately not emitted).
1724 sub _cmd_printf {
1725 my ($rest) = @_;
1726 $rest = '' unless defined $rest;
1727  
1728 my @tok = _arr_split_words($rest);
1729  
1730 # Options on the still-quoted tokens: -v VAR / -vVAR, and -- terminator.
1731 my $target;
1732 while (@tok) {
1733 my $t0 = $tok[0];
1734 if ($t0 eq '--') { shift @tok; last }
1735 if ($t0 eq '-v') {
1736 shift @tok;
1737 my $vn = @tok ? _arr_dequote(shift @tok) : '';
1738 $target = $vn if $vn ne '';
1739 next;
1740 }
1741 if ($t0 =~ /\A-v(.+)\z/s) {
1742 shift @tok;
1743 $target = _arr_dequote($1);
1744 next;
1745 }
1746 last;
1747 }
1748 if (!@tok) { $LAST_STATUS = 0; return 0 }
1749  
1750 my $fmt = _arr_dequote(shift @tok);
1751 my @args = map { _arr_dequote($_) } @tok;
1752 $fmt = BATsh::MB::dec($fmt);
1753 @args = map { BATsh::MB::dec($_) } @args;
1754  
1755 my ($fmt_x, $fmt_stop) = _printf_unescape($fmt, 1);
1756 my $out = _printf_format($fmt_x, $fmt_stop, @args);
1757  
1758 if (defined $target) {
1759 BATsh::Env->set($target, $out);
1760 }
1761 else {
1762 print $out;
1763 }
1764 $LAST_STATUS = 0;
1765 return 0;
1766 }
1767  
1768 # _printf_unescape(STR, ALLOW_C): interpret C/POSIX backslash escapes.
1769 # Returns (RESULT, STOP) where STOP is true when a "\c" (only recognised
1770 # when ALLOW_C is set) requested that output cease. Unknown escapes keep
1771 # their backslash, matching bash.
1772 sub _printf_unescape {
1773 my ($s, $allow_c) = @_;
1774 $s = '' unless defined $s;
1775 my $out = '';
1776 my $stop = 0;
1777 my $i = 0;
1778 my $n = length $s;
1779 while ($i < $n) {
1780 my $c = substr($s, $i, 1);
1781 if ($c ne '\\') { $out .= $c; $i++; next }
1782 my $d = substr($s, $i + 1, 1);
1783 if ($d eq 'n') { $out .= "\n"; $i += 2 }
1784 elsif ($d eq 't') { $out .= "\t"; $i += 2 }
1785 elsif ($d eq 'r') { $out .= "\r"; $i += 2 }
1786 elsif ($d eq '\\') { $out .= "\\"; $i += 2 }
1787 elsif ($d eq 'a') { $out .= chr(7); $i += 2 }
1788 elsif ($d eq 'b') { $out .= chr(8); $i += 2 }
1789 elsif ($d eq 'f') { $out .= chr(12); $i += 2 }
1790 elsif ($d eq 'v') { $out .= chr(11); $i += 2 }
1791 elsif ($d eq 'e' || $d eq 'E') { $out .= chr(27); $i += 2 }
1792 elsif ($d eq '"') { $out .= '"'; $i += 2 }
1793 elsif ($d eq "'") { $out .= "'"; $i += 2 }
1794 elsif ($d eq 'c' && $allow_c) { $stop = 1; last }
1795 elsif ($d eq 'x') {
1796 my $h = substr($s, $i + 2);
1797 if ($h =~ /\A([0-9A-Fa-f]{1,2})/) {
1798 $out .= chr(hex($1)); $i += 2 + length($1);
1799 }
1800 else { $out .= '\\x'; $i += 2 }
1801 }
1802 elsif ($d =~ /[0-7]/) {
1803 my $o = substr($s, $i + 1);
1804 if ($o =~ /\A(0?[0-7]{1,3})/) {
1805 $out .= chr(oct($1) & 0xFF); $i += 1 + length($1);
1806 }
1807 else { $out .= '\\'; $i++ }
1808 }
1809 elsif ($d eq '') { $out .= '\\'; $i++ }
1810 else { $out .= '\\' . $d; $i += 2 }
1811 }
1812 return ($out, $stop);
1813 }
1814  
1815 # _printf_int(STR) / _printf_num(STR): coerce a printf argument to an
1816 # integer / a number for a numeric conversion. A leading ' or " selects
1817 # the numeric value of the following character (POSIX); otherwise a leading
1818 # numeric prefix (decimal, 0x hex, 0 octal) is used, and a non-numeric
1819 # argument yields 0 (bash warns and uses 0; we stay quiet).
1820 sub _printf_int {
1821 my ($s) = @_;
1822 $s = '' unless defined $s;
1823 if ($s =~ /\A['"](.)/s) { return ord($1) }
1824 if ($s =~ /\A\s*([-+]?)0[xX]([0-9A-Fa-f]+)/) {
1825 my $v = hex($2); return ($1 eq '-') ? -$v : $v;
1826 }
1827 if ($s =~ /\A\s*([-+]?)0([0-7]+)\z/) {
1828 my $v = oct($2); return ($1 eq '-') ? -$v : $v;
1829 }
1830 if ($s =~ /\A\s*([-+]?\d+)/) { return int($1) }
1831 return 0;
1832 }
1833  
1834 sub _printf_num {
1835 my ($s) = @_;
1836 $s = '' unless defined $s;
1837 if ($s =~ /\A['"](.)/s) { return ord($1) }
1838 if ($s =~ /\A\s*([-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?)/) { return $1 + 0 }
1839 if ($s =~ /\A\s*([-+]?)0[xX]([0-9A-Fa-f]+)/) {
1840 my $v = hex($2); return ($1 eq '-') ? -$v : $v;
1841 }
1842 return 0;
1843 }
1844  
1845 # _printf_shellquote(STR): the "%q" conversion -- quote STR so it reads back
1846 # as a single shell word. Safe characters are emitted bare; anything else
1847 # is single-quoted with embedded single quotes rendered as '\''.
1848 sub _printf_shellquote {
1849 my ($s) = @_;
1850 $s = '' unless defined $s;
1851 return "''" if $s eq '';
1852 return $s if $s =~ m{\A[-A-Za-z0-9_./:=@%+,]+\z};
1853 my $q = $s;
1854 $q =~ s/'/'\\''/g;
1855 return "'" . $q . "'";
1856 }
1857  
1858 # _sp(FMT, ARGS): sprintf with warnings suppressed (a non-numeric argument
1859 # already coerced to 0, an over-wide field, etc. must not print to STDERR).
1860 sub _sp {
1861 my ($f, @a) = @_;
1862 local $SIG{'__WARN__'} = sub { };
1863 return sprintf($f, @a);
1864 }
1865  
1866 # _printf_format(FMT, FMT_STOP, ARGS): apply the (already escape-expanded)
1867 # format to the argument list, recycling the format until the arguments are
1868 # exhausted (bash semantics), and stopping early if a "\c" was seen.
1869 sub _printf_format {
1870 my ($fmt, $fmt_stop, @args) = @_;
1871 my $out = '';
1872 my $ai = 0;
1873 my $narg = scalar @args;
1874 my $guard = 0;
1875 while (1) {
1876 $guard++;
1877 last if $guard > 100000;
1878 my $consumed = 0;
1879 my $stop = 0;
1880 my $i = 0;
1881 my $len = length $fmt;
1882 while ($i < $len) {
1883 my $c = substr($fmt, $i, 1);
1884 if ($c ne '%') { $out .= $c; $i++; next }
1885 if (substr($fmt, $i + 1, 1) eq '%') { $out .= '%'; $i += 2; next }
1886 my $tail = substr($fmt, $i);
1887 if ($tail =~ /\A(%[-+ 0#]*(?:\*|\d+)?(?:\.(?:\*|\d+))?)([diouxXeEfgGcsbq])/) {
1888 my $spec = $1;
1889 my $conv = $2;
1890 $i += length($1) + length($2);
1891  
1892 while ($spec =~ /\*/) {
1893 my $val = ($ai < $narg) ? _printf_int($args[$ai]) : 0;
1894 if ($ai < $narg) { $ai++; $consumed++ }
1895 $val = -$val if $val < 0; # negative field width -> abs
1896 $spec =~ s/\*/$val/;
1897 }
1898  
1899 my $have = ($ai < $narg);
1900 my $raw = $have ? $args[$ai] : '';
1901  
1902 if ($conv eq 's') {
1903 $out .= _sp($spec . 's', $raw);
1904 if ($have) { $ai++; $consumed++ }
1905 }
1906 elsif ($conv eq 'b') {
1907 my ($ex, $st) = _printf_unescape($raw, 1);
1908 $out .= _sp($spec . 's', $ex);
1909 if ($have) { $ai++; $consumed++ }
1910 if ($st) { $stop = 1; last }
1911 }
1912 elsif ($conv eq 'q') {
1913 $out .= _sp($spec . 's', _printf_shellquote($raw));
1914 if ($have) { $ai++; $consumed++ }
1915 }
1916 elsif ($conv eq 'c') {
1917 my $ch = length($raw) ? substr($raw, 0, 1) : '';
1918 $out .= _sp($spec . 's', $ch);
1919 if ($have) { $ai++; $consumed++ }
1920 }
1921 elsif ($conv =~ /[diouxX]/) {
1922 $out .= _sp($spec . $conv, _printf_int($raw));
1923 if ($have) { $ai++; $consumed++ }
1924 }
1925 else {
1926 $out .= _sp($spec . $conv, _printf_num($raw));
1927 if ($have) { $ai++; $consumed++ }
1928 }
1929 }
1930 else { $out .= '%'; $i++ }
1931 }
1932 last if $stop || $fmt_stop;
1933 last unless ($ai < $narg && $consumed > 0);
1934 }
1935 return $out;
1936 }
1937  
1938 # ----------------------------------------------------------------
1939 # Tilde expansion (v0.07): ~/path and ~user/path.
1940 #
1941 # POSIX word-initial tilde expansion. Only applied to a word that
1942 # begins with an UNQUOTED ~ (callers are responsible for that check);
1943 # the tilde-prefix itself is never subject to variable / command
1944 # substitution. Forms:
1945 # ~ -> $HOME
1946 # ~/rest -> $HOME . '/rest'
1947 # ~user -> user's home directory (getpwnam; Unix-like only)
1948 # ~user/rest -> that directory . '/rest'
1949 # If the login name is unknown (or getpwnam is unavailable, as on
1950 # Win32) the word is returned unchanged, matching bash's behaviour of
1951 # leaving an unresolvable ~name literal.
1952 # NOT implemented: colon-list tilde expansion in PATH-like assignments
1953 # (bash also tilde-expands after ':' in PATH=~/a:~/b); documented as a
1954 # limitation in the POD.
1955 # ----------------------------------------------------------------
1956 sub _tilde_expand {
1957 my ($word) = @_;
1958 return $word unless defined $word && $word =~ /\A~/;
1959 my ($tag, $rest) = ($word =~ /\A~([^\/]*)(.*)\z/s);
1960 $tag = '' unless defined $tag;
1961 $rest = '' unless defined $rest;
1962 my $home;
1963 if ($tag eq '') {
1964 $home = $ENV{'HOME'};
1965 $home = BATsh::Env->get('HOME') unless defined $home && $home ne '';
1966 }
1967 elsif ($^O !~ /MSWin32/i) {
1968 my @pw = eval { getpwnam($tag) };
1969 $home = (!$@ && @pw) ? $pw[7] : undef;
1970 }
1971 return $word unless defined $home && $home ne '';
1972 return $home . $rest;
1973 }
1974  
1975 # _tilde_prepass: scan a RAW (not-yet-variable-expanded) string and
1976 # expand every unquoted, word-initial "~..." run using _tilde_expand().
1977 # A "word start" is: the very beginning of the string, any position
1978 # right after unquoted whitespace, or (once, at the very beginning of
1979 # the string only) the position right after the '=' of a leading
1980 # NAME= assignment token -- matching bash's extra tilde-expansion spot
1981 # for VAR=~/path. Quoted text (single or double quotes) is copied
1982 # through untouched and never considered a word start for tilde
1983 # purposes. Everything else in the string (variables, command
1984 # substitution, arithmetic, ...) is left as-is for the rest of
1985 # _expand() to process afterwards.
1986 # _tilde_protect: let an expanded tilde-prefix survive the rest of the
1987 # expansion pipeline unharmed. The replacement text is DATA, not shell
1988 # source: a Windows home directory such as C:\home\flower must not have
1989 # its backslashes eaten by quote removal, a "$" or "`" in it must not
1990 # start an expansion, and a home directory containing spaces must stay
1991 # a single word (POSIX: a tilde-expansion result is not field-split).
1992 # An unresolved ~name is returned untouched, exactly as bash leaves it.
1993 sub _tilde_protect {
1994 my ($expanded, $orig) = @_;
1995 return $orig unless defined $expanded;
1996 return $expanded if $expanded eq $orig;
1997 my $v = _protect_lit($expanded);
1998 $v =~ s/\$/\x00BATSH_DL\x00/g;
1999 $v =~ s/`/\x00BATSH_BT\x00/g;
2000 # Only a home directory containing whitespace needs the quotes;
2001 # quoting the usual case too would suppress globbing of ~/* words.
2002 return $v unless $v =~ /\s/;
2003 return '"' . $v . '"';
2004 }
2005  
2006 sub _tilde_prepass {
2007 my ($str) = @_;
2008  
2009 return $str unless defined $str && $str =~ /~/;
2010  
2011 my @chars = split //, $str;
2012 my $n = scalar @chars;
2013 my $out = '';
2014 my $i = 0;
2015  
2016 # Leading NAME= assignment token: the char right after '=' is also
2017 # a valid tilde-expansion start, but only for this one leading token.
2018 if ($str =~ /\A([A-Za-z_][A-Za-z0-9_]*=)/) {
2019 my $prefix = $1;
2020 $out .= $prefix;
2021 $i = length($prefix);
2022 }
2023  
2024 my $at_word_start = 1;
2025 my $in_sq = 0;
2026 my $in_dq = 0;
2027 while ($i < $n) {
2028 my $c = $chars[$i];
2029 if ($in_sq) { $out .= $c; $in_sq = 0 if $c eq "'"; $i++; $at_word_start = 0; next }
2030 if ($in_dq) { $out .= $c; $in_dq = 0 if $c eq '"'; $i++; $at_word_start = 0; next }
2031 if ($c eq "'") { $in_sq = 1; $out .= $c; $i++; $at_word_start = 0; next }
2032 if ($c eq '"') { $in_dq = 1; $out .= $c; $i++; $at_word_start = 0; next }
2033 if ($c =~ /\s/) { $out .= $c; $i++; $at_word_start = 1; next }
2034 if ($at_word_start && $c eq '~') {
2035 my $j = $i + 1;
2036 my $tag = '';
2037 while ($j < $n && $chars[$j] !~ /[\s\/'"]/) { $tag .= $chars[$j]; $j++ }
2038 $out .= _tilde_protect(_tilde_expand('~' . $tag), '~' . $tag);
2039 $i = $j;
2040 $at_word_start = 0;
2041 next;
2042 }
2043 $out .= $c;
2044 $i++;
2045 $at_word_start = 0;
2046 }
2047 return $out;
2048 }
2049  
2050 # ----------------------------------------------------------------
2051 # Brace expansion (v0.07): {a,b,c} and {1..5} / {a..e} [..step] word
2052 # generation. Runs on the RAW source line, lexically, before any other
2053 # expansion -- exactly like the tilde prepass above. Quoted text and
2054 # anything that is opaque shell syntax (${...}, $(...), $((...)), `...`,
2055 # <(...), >(...), and backslash-escaped characters) is protected behind
2056 # a NUL-delimited sentinel so its content is copied through untouched
2057 # and its internal whitespace never becomes a false word boundary.
2058 # ----------------------------------------------------------------
2059 sub _brace_expand_line {
2060 my ($line) = @_;
2061 return $line unless defined $line && $line =~ /\{/;
2062  
2063 my @protected;
2064 my $safe = '';
2065 my @c = split //, $line;
2066 my $n = scalar @c;
2067 my $i = 0;
2068 while ($i < $n) {
2069 my $ch = $c[$i];
2070  
2071 if ($ch eq '\\') {
2072 my $seg = $ch . (($i+1 < $n) ? $c[$i+1] : '');
2073 push @protected, $seg;
2074 $safe .= "\x00BR" . $#protected . "\x00";
2075 $i += 2; next;
2076 }
2077 if ($ch eq "'") {
2078 my $j = $i + 1;
2079 while ($j < $n && $c[$j] ne "'") { $j++ }
2080 $j++ if $j < $n;
2081 my $seg = join('', @c[$i .. $j-1]);
2082 push @protected, $seg;
2083 $safe .= "\x00BR" . $#protected . "\x00";
2084 $i = $j; next;
2085 }
2086 if ($ch eq '"') {
2087 my $j = $i + 1;
2088 while ($j < $n && $c[$j] ne '"') {
2089 $j += ($c[$j] eq '\\' && $j+1 < $n) ? 2 : 1;
2090 }
2091 $j++ if $j < $n;
2092 my $seg = join('', @c[$i .. $j-1]);
2093 push @protected, $seg;
2094 $safe .= "\x00BR" . $#protected . "\x00";
2095 $i = $j; next;
2096 }
2097 if ($ch eq '$' && $i+1 < $n && ($c[$i+1] eq '(' || $c[$i+1] eq '{')) {
2098 my $openc = $c[$i+1];
2099 my $closec = ($openc eq '(') ? ')' : '}';
2100 my $depth = 1;
2101 my $j = $i + 2;
2102 while ($j < $n && $depth > 0) {
2103 if ($c[$j] eq $openc) { $depth++ }
2104 elsif ($c[$j] eq $closec) { $depth-- }
2105 $j++;
2106 }
2107 my $seg = join('', @c[$i .. $j-1]);
2108 push @protected, $seg;
2109 $safe .= "\x00BR" . $#protected . "\x00";
2110 $i = $j; next;
2111 }
2112 if (($ch eq '<' || $ch eq '>') && $i+1 < $n && $c[$i+1] eq '(') {
2113 my $depth = 1;
2114 my $j = $i + 2;
2115 while ($j < $n && $depth > 0) {
2116 if ($c[$j] eq '(') { $depth++ }
2117 elsif ($c[$j] eq ')') { $depth-- }
2118 $j++;
2119 }
2120 my $seg = join('', @c[$i .. $j-1]);
2121 push @protected, $seg;
2122 $safe .= "\x00BR" . $#protected . "\x00";
2123 $i = $j; next;
2124 }
2125 if ($ch eq '`') {
2126 my $j = $i + 1;
2127 while ($j < $n && $c[$j] ne '`') { $j++ }
2128 $j++ if $j < $n;
2129 my $seg = join('', @c[$i .. $j-1]);
2130 push @protected, $seg;
2131 $safe .= "\x00BR" . $#protected . "\x00";
2132 $i = $j; next;
2133 }
2134  
2135 $safe .= $ch; $i++;
2136 }
2137  
2138 my @pieces = split /(\s+)/, $safe;
2139 my $out = '';
2140 for my $w (@pieces) {
2141 if ($w eq '' || $w =~ /\A\s+\z/) { $out .= $w; next }
2142 my @exp = ($w =~ /\{/) ? _brace_expand_word($w) : ($w);
2143 $out .= join(' ', @exp);
2144 }
2145  
2146 $out =~ s/\x00BR(\d+)\x00/$protected[$1]/ge;
2147 return $out;
2148 }
2149  
2150 # _brace_expand_word: expand all brace groups in one already-protected
2151 # word, returning the list of resulting words (a single-element list
2152 # containing the word unchanged when it holds no valid brace group).
2153 sub _brace_expand_word {
2154 my ($word) = @_;
2155 return ($word) unless defined $word && $word =~ /\{/;
2156 my @found = _brace_find_group($word, 0);
2157 return ($word) unless @found;
2158 my ($open, $close, $alts_ref) = @found;
2159 my $prefix = substr($word, 0, $open);
2160 my $suffix = substr($word, $close + 1);
2161 my @suffix_words = _brace_expand_word($suffix);
2162 my @out;
2163 for my $a (@{$alts_ref}) {
2164 for my $aw (_brace_expand_word($a)) {
2165 for my $sw (@suffix_words) {
2166 push @out, $prefix . $aw . $sw;
2167 }
2168 }
2169 }
2170 return @out;
2171 }
2172  
2173 # _brace_find_group: locate the first VALID brace group at or after
2174 # $start (a comma-list or a range -- a bare "{word}" with neither is
2175 # left as literal text and scanning continues past it). Returns
2176 # ($open_pos, $close_pos, \@alternatives) or () when none remain.
2177 sub _brace_find_group {
2178 my ($word, $start) = @_;
2179 my @c = split //, $word;
2180 my $n = scalar @c;
2181 my $i = $start;
2182 while ($i < $n) {
2183 if ($c[$i] eq '\\') { $i += 2; next }
2184 if ($c[$i] ne '{') { $i++; next }
2185  
2186 my $open = $i;
2187 my $depth = 1;
2188 my $j = $i + 1;
2189 my @commas;
2190 while ($j < $n && $depth > 0) {
2191 if ($c[$j] eq '\\') { $j += 2; next }
2192 if ($c[$j] eq '{') { $depth++; $j++; next }
2193 if ($c[$j] eq '}') { $depth--; $j++; next }
2194 if ($c[$j] eq ',' && $depth == 1) { push @commas, $j }
2195 $j++;
2196 }
2197 if ($depth != 0) { $i = $open + 1; next } # unmatched '{'
2198  
2199 my $close = $j - 1;
2200 my @alts;
2201 if (@commas) {
2202 my $prev = $open + 1;
2203 for my $pos (@commas) {
2204 push @alts, substr($word, $prev, $pos - $prev);
2205 $prev = $pos + 1;
2206 }
2207 push @alts, substr($word, $prev, $close - $prev);
2208 }
2209 else {
2210 @alts = _brace_expand_range(substr($word, $open + 1, $close - $open - 1));
2211 }
2212 return ($open, $close, \@alts) if @alts;
2213 $i = $open + 1; # not a valid group: keep scanning past it
2214 }
2215 return ();
2216 }
2217  
2218 # _brace_expand_range: expand "X..Y" or "X..Y..STEP" -- integer (with
2219 # optional zero-padding taken from the wider operand) or single-letter.
2220 # Returns () when $inner is not a recognised range expression.
2221 sub _brace_expand_range {
2222 my ($inner) = @_;
2223 $inner = '' unless defined $inner;
2224  
2225 if ($inner =~ /\A(-?\d+)\.\.(-?\d+)(?:\.\.(-?\d+))?\z/) {
2226 my ($from, $to, $step) = ($1, $2, $3);
2227 my $pad = 0;
2228 if ($from =~ /\A-?0\d/ || $to =~ /\A-?0\d/) {
2229 my $w1 = length($from); $w1-- if substr($from, 0, 1) eq '-';
2230 my $w2 = length($to); $w2-- if substr($to, 0, 1) eq '-';
2231 $pad = ($w1 > $w2) ? $w1 : $w2;
2232 }
2233 $step = 1 unless defined $step && $step != 0;
2234 $step = -$step if $step > 0 && $from > $to;
2235 $step = -$step if $step < 0 && $from < $to;
2236 my @out;
2237 if ($step > 0) { for (my $v=$from; $v<=$to; $v+=$step) { push @out, _brace_pad($v, $pad) } }
2238 else { for (my $v=$from; $v>=$to; $v+=$step) { push @out, _brace_pad($v, $pad) } }
2239 return @out;
2240 }
2241 if ($inner =~ /\A([A-Za-z])\.\.([A-Za-z])(?:\.\.(-?\d+))?\z/) {
2242 my ($from, $to, $step) = ($1, $2, $3);
2243 $step = 1 unless defined $step && $step != 0;
2244 $step = abs($step);
2245 my ($fo, $to_o) = (ord($from), ord($to));
2246 my @out;
2247 if ($fo <= $to_o) { for (my $v=$fo; $v<=$to_o; $v+=$step) { push @out, chr($v) } }
2248 else { for (my $v=$fo; $v>=$to_o; $v-=$step) { push @out, chr($v) } }
2249 return @out;
2250 }
2251 return ();
2252 }
2253  
2254 sub _brace_pad {
2255 my ($v, $pad) = @_;
2256 return $v unless $pad;
2257 my $neg = ($v < 0) ? 1 : 0;
2258 my $s = sprintf('%0' . $pad . 'd', $neg ? -$v : $v);
2259 return $neg ? "-$s" : $s;
2260 }
2261  
2262 # ----------------------------------------------------------------
2263 # cd
2264 # ----------------------------------------------------------------
2265 sub _cmd_cd {
2266 my ($rest) = @_;
2267 $rest =~ s/\A\s+//;
2268 $rest =~ s/\s+\z//;
2269 # Strip quotes the same way command words are dequoted, so
2270 # cd "a b" / cd 'dir' / cd "$HOME/x" reach chdir() as a plain path.
2271 $rest = _arr_dequote($rest);
2272 $rest = BATsh::MB::dec($rest);
2273 if ($rest eq '') {
2274 $rest = $ENV{'HOME'} || BATsh::Env->get('HOME') || '.';
2275 }
2276 unless (chdir($rest)) {
2277 print STDERR "cd: $rest: No such file or directory\n";
2278 $LAST_STATUS = 1;
2279 return 1;
2280 }
2281 BATsh::Env->set('PWD', BATsh::MB::enc(Cwd::cwd()));
2282 $LAST_STATUS = 0;
2283 return 0;
2284 }
2285  
2286 # ----------------------------------------------------------------
2287 # exit
2288 # ----------------------------------------------------------------
2289 sub _cmd_exit {
2290 my ($rest) = @_;
2291 $rest =~ s/\A\s+//;
2292 my $code = ($rest =~ /\A(\d+)/) ? int($1) : 0;
2293 # Run the EXIT trap (once) before exiting, while no exit is yet pending so
2294 # the trap body executes. Delete it first to avoid re-entry / double-fire.
2295 if (exists $_SH_TRAP{'EXIT'}) {
2296 my $cmd = delete $_SH_TRAP{'EXIT'};
2297 if (defined $cmd && $cmd ne '') {
2298 eval { _run_lines('BATsh::SH', [$cmd], {}) };
2299 }
2300 }
2301 $_EXIT_CODE = $code;
2302 $LAST_STATUS = $code;
2303 return $code;
2304 }
2305  
2306 # ----------------------------------------------------------------
2307 # exec (v0.07)
2308 #
2309 # exec > file / exec 2>&1 / ... apply redirection(s) permanently to
2310 # the current shell (no save/restore)
2311 # exec cmd args... run cmd (with its own redirections,
2312 # if any) then terminate the whole
2313 # script with cmd's exit status
2314 #
2315 # There is no real fork/exec here (this interpreter is Pure Perl and
2316 # never forks -- see the Background Execution / Compound Commands notes
2317 # above); "replacing the shell" is approximated by ending the script
2318 # immediately afterward, and redirections are applied by permanently
2319 # reassigning the STDIN/STDOUT/STDERR bareword globs instead of the
2320 # save-and-restore dance _sh_exec_with_redirs() uses for ordinary
2321 # commands.
2322 # ----------------------------------------------------------------
2323 sub _cmd_exec {
2324 my ($class, $rest, $opts_ref) = @_;
2325 $rest = '' unless defined $rest;
2326 my ($clean, $redirs_ref) = _sh_strip_redirects($rest);
2327  
2328 for my $r (@{$redirs_ref}) {
2329 my ($fd, $append, $file) = @{$r};
2330 $file = BATsh::MB::dec($file) unless $file =~ /\A&[12]\z/;
2331 my $ok = 1;
2332 if ($fd == 0) {
2333 # sysopen() takes the filename literally -- a leading '>' or a
2334 # trailing '|' is never treated as a mode or a pipe command.
2335 $ok = sysopen(STDIN, $file, O_RDONLY);
2336 }
2337 elsif ($fd == 1) {
2338 $ok = ($file eq '&2')
2339 ? open(STDOUT, '>&STDERR')
2340 : sysopen(STDOUT, $file,
2341 O_WRONLY | O_CREAT | ($append ? O_APPEND : O_TRUNC), 0666);
2342 }
2343 else {
2344 $ok = ($file eq '&1')
2345 ? open(STDERR, '>&STDOUT')
2346 : sysopen(STDERR, $file,
2347 O_WRONLY | O_CREAT | ($append ? O_APPEND : O_TRUNC), 0666);
2348 }
2349 unless ($ok) {
2350 warn "sh: exec: $file: $!\n";
2351 $LAST_STATUS = 1;
2352 return 1;
2353 }
2354 }
2355  
2356 $clean =~ s/\A\s+//; $clean =~ s/\s+\z//;
2357 if ($clean eq '') {
2358 # "exec" with only redirections: they now apply for the rest of
2359 # the script; exec itself does not terminate anything.
2360 $LAST_STATUS = 0;
2361 return 0;
2362 }
2363  
2364 my $rc = _exec_line($class, $clean, $opts_ref);
2365 $_EXIT_CODE = $rc; # exec replaces the shell: end the script here
2366 $LAST_STATUS = $rc;
2367 return $rc;
2368 }
2369  
2370 # ----------------------------------------------------------------
2371 # trap -- signal / event handling (v0.06)
2372 #
2373 # Supported forms:
2374 # trap 'commands' SIGSPEC... register a handler
2375 # trap - SIGSPEC... reset to the default action
2376 # trap '' SIGSPEC... ignore the signal
2377 # trap / trap -p list the current traps
2378 #
2379 # SIGSPEC may be a name (with or without a leading SIG), a number, or the
2380 # EXIT pseudo-signal (also spelled 0). Real OS signals are bridged to
2381 # Perl's %SIG; EXIT is run internally when the script ends or on `exit`.
2382 # The handler command is stored unexpanded and (re-)expanded when it fires.
2383 # ----------------------------------------------------------------
2384 sub _cmd_trap {
2385 my ($class, $rest, $opts_ref) = @_;
2386 my ($mode, $cmd, $sigs) = _sh_parse_trap($rest);
2387  
2388 if ($mode eq 'list') {
2389 my @names = @{$sigs} ? @{$sigs} : sort keys %_SH_TRAP;
2390 for my $n (@names) {
2391 my $sig = _sh_normalize_sig($n);
2392 next unless exists $_SH_TRAP{$sig};
2393 print "trap -- '" . $_SH_TRAP{$sig} . "' $sig\n";
2394 }
2395 $LAST_STATUS = 0;
2396 return 0;
2397 }
2398  
2399 for my $spec (@{$sigs}) {
2400 my $sig = _sh_normalize_sig($spec);
2401 next if $sig eq '';
2402 if ($mode eq 'reset') {
2403 delete $_SH_TRAP{$sig};
2404 _sh_set_os_sig($sig, 'DEFAULT');
2405 }
2406 elsif ($mode eq 'ignore') {
2407 $_SH_TRAP{$sig} = '';
2408 _sh_set_os_sig($sig, 'IGNORE');
2409 }
2410 else { # set
2411 $_SH_TRAP{$sig} = $cmd;
2412 _sh_set_os_sig($sig, 'HANDLER');
2413 }
2414 }
2415 $LAST_STATUS = 0;
2416 return 0;
2417 }
2418  
2419 # Parse the (raw) argument string of a trap command.
2420 # Returns ($mode, $cmd, \@sigs) where $mode is 'list', 'reset', 'ignore'
2421 # or 'set'. For 'set', $cmd is the (still unexpanded) handler command.
2422 sub _sh_parse_trap {
2423 my ($s) = @_;
2424 $s = '' unless defined $s;
2425 $s =~ s/\A\s+//; $s =~ s/\s+\z//;
2426 return ('list', undef, []) if $s eq '';
2427  
2428 if ($s =~ /\A-p\b\s*(.*)\z/s) {
2429 my @sigs = grep { length } split /\s+/, $1;
2430 return ('list', undef, \@sigs);
2431 }
2432  
2433 my ($action, $quoted, $rest);
2434 if ($s =~ /\A'([^']*)'\s*(.*)\z/s) {
2435 ($action, $quoted, $rest) = ($1, 1, $2);
2436 }
2437 elsif ($s =~ /\A"((?:[^"\\]|\\.)*)"\s*(.*)\z/s) {
2438 ($action, $quoted, $rest) = ($1, 1, $2);
2439 }
2440 else {
2441 ($action, $rest) = split /\s+/, $s, 2;
2442 $quoted = 0;
2443 $rest = '' unless defined $rest;
2444 }
2445 my @sigs = grep { length } split /\s+/, $rest;
2446  
2447 return ('reset', undef, \@sigs) if !$quoted && $action eq '-';
2448 return ('ignore', '', \@sigs) if $quoted && $action eq '';
2449 return ('set', $action, \@sigs);
2450 }
2451  
2452 # Normalize a signal spec to a bare name: strip a leading SIG, uppercase,
2453 # and map the common signal numbers to names.
2454 sub _sh_normalize_sig {
2455 my ($s) = @_;
2456 return '' unless defined $s;
2457 $s =~ s/\A\s+//; $s =~ s/\s+\z//;
2458 return '' if $s eq '';
2459 $s = uc($s);
2460 $s =~ s/\ASIG//;
2461 if ($s =~ /\A\d+\z/) {
2462 my %num = (0 => 'EXIT', 1 => 'HUP', 2 => 'INT', 3 => 'QUIT',
2463 6 => 'ABRT', 9 => 'KILL', 13 => 'PIPE', 14 => 'ALRM',
2464 15 => 'TERM');
2465 $s = exists $num{$s + 0} ? $num{$s + 0} : $s;
2466 }
2467 return $s;
2468 }
2469  
2470 # Bridge a trap to Perl's %SIG. Pseudo-signals (EXIT/ERR/DEBUG/RETURN) are
2471 # handled internally and never touch %SIG. Assignment is eval-guarded so an
2472 # unsupported signal name (e.g. on Windows) degrades quietly.
2473 sub _sh_set_os_sig {
2474 my ($sig, $what) = @_;
2475 return if $sig eq 'EXIT' || $sig eq 'ERR'
2476 || $sig eq 'DEBUG' || $sig eq 'RETURN';
2477 # Some signals (e.g. HUP/USR1/USR2) do not exist on every platform --
2478 # notably Windows -- where assigning to %SIG for them emits a harmless
2479 # "No such signal" warning. Suppress just that warning so a portable
2480 # script trapping such a signal stays quiet; all other warnings pass
2481 # through, and the assignment itself still succeeds (best effort).
2482 local $SIG{__WARN__} = sub {
2483 my $w = defined $_[0] ? $_[0] : '';
2484 warn $w unless $w =~ /No such signal/;
2485 };
2486 eval {
2487 if ($what eq 'DEFAULT') { $SIG{$sig} = 'DEFAULT' }
2488 elsif ($what eq 'IGNORE') { $SIG{$sig} = 'IGNORE' }
2489 else { $SIG{$sig} = sub { _sh_run_trap($sig) } }
2490 };
2491 return;
2492 }
2493  
2494 # Run the handler command registered for $sig (no-op if unset or 'ignore').
2495 sub _sh_run_trap {
2496 my ($sig) = @_;
2497 my $cmd = $_SH_TRAP{$sig};
2498 return unless defined $cmd && $cmd ne '';
2499 eval { _run_lines('BATsh::SH', [$cmd], {}) };
2500 }
2501  
2502 # Run the EXIT trap (if any) exactly once, then clear it. Called by the
2503 # top-level run paths in BATsh.pm when the whole script has finished.
2504 sub fire_exit_trap {
2505 my ($class) = @_;
2506 return unless exists $_SH_TRAP{'EXIT'};
2507 my $cmd = delete $_SH_TRAP{'EXIT'};
2508 return if !defined $cmd || $cmd eq '';
2509 $_EXIT_CODE = undef; # let the trap body run to completion
2510 eval { _run_lines('BATsh::SH', [$cmd], {}) };
2511 return;
2512 }
2513  
2514 # ----------------------------------------------------------------
2515 # read
2516 # ----------------------------------------------------------------
2517 sub _cmd_read {
2518 my ($rest) = @_;
2519 $rest = '' unless defined $rest;
2520 $rest =~ s/\A\s+//;
2521 $rest =~ s/\s+\z//;
2522  
2523 # Drop option flags such as -r (we always read a raw line); only the
2524 # bareword names that follow are treated as target variables.
2525 my @vars = grep { length && !/\A-/ } split /\s+/, $rest;
2526  
2527 my $line = <STDIN>;
2528 $line = BATsh::MB::enc($line) if defined $line;
2529 if (!defined $line) {
2530 # End of input. POSIX read returns non-zero at EOF so that a
2531 # 'while read VAR; do ...; done < file' loop terminates instead
2532 # of spinning forever.
2533 for my $v (@vars) { BATsh::Env->set($v, '') }
2534 $LAST_STATUS = 1;
2535 return 1;
2536 }
2537 chomp $line;
2538  
2539 if (@vars == 1) {
2540 BATsh::Env->set($vars[0], $line);
2541 }
2542 elsif (@vars > 1) {
2543 my @words = split /\s+/, $line, scalar(@vars);
2544 for my $i (0 .. $#vars) {
2545 BATsh::Env->set($vars[$i], defined($words[$i]) ? $words[$i] : '');
2546 }
2547 }
2548 $LAST_STATUS = 0;
2549 return 0;
2550 }
2551  
2552 # ----------------------------------------------------------------
2553 # shift
2554 # ----------------------------------------------------------------
2555 sub _cmd_shift {
2556 my ($rest) = @_;
2557 $rest = '' unless defined $rest;
2558 $rest =~ s/\A\s+//;
2559  
2560 # Optional /N offset (bash: shift N shifts N positions)
2561 my $n_shift = 1;
2562 if ($rest =~ /\A(\d+)\s*\z/) { $n_shift = int($1); $n_shift = 1 if $n_shift < 1 }
2563  
2564 for my $step (1 .. $n_shift) {
2565 # Shift BATSH_ARG* (legacy)
2566 for my $n (1 .. 8) {
2567 my $next = BATsh::Env->get('BATSH_ARG' . ($n + 1));
2568 BATsh::Env->set('BATSH_ARG' . $n, defined($next) ? $next : '');
2569 }
2570 BATsh::Env->set('BATSH_ARG9', '');
2571  
2572 # Shift %1..%9 (used by _expand $1..$9)
2573 for my $n (1 .. 8) {
2574 my $next = BATsh::Env->get('%' . ($n + 1));
2575 BATsh::Env->set('%' . $n, defined($next) ? $next : '');
2576 }
2577 BATsh::Env->set('%9', '');
2578  
2579 # Rebuild %*
2580 my @args;
2581 for my $n (1 .. 9) {
2582 my $v = BATsh::Env->get("%$n");
2583 last unless defined $v && $v ne '';
2584 push @args, $v;
2585 }
2586 BATsh::Env->set('%*', join(' ', @args));
2587 }
2588 $LAST_STATUS = 0;
2589 return 0;
2590 }
2591  
2592 # ----------------------------------------------------------------
2593 # getopts optstring name [arg ...]
2594 # ----------------------------------------------------------------
2595 # POSIX option parser. Called once per option in a loop:
2596 #
2597 # while getopts "ab:c" opt; do
2598 # case $opt in
2599 # a) ... ;;
2600 # b) echo "$OPTARG" ;;
2601 # c) ... ;;
2602 # \?) echo "bad option" >&2 ;;
2603 # esac
2604 # done
2605 # shift $((OPTIND - 1))
2606 #
2607 # Sets the variable named by the second argument to the option letter
2608 # found (or '?' on an unknown option, or ':' on a missing argument when
2609 # the optstring begins with ':'). OPTARG receives an option's argument;
2610 # OPTIND advances to the next argument to be processed. Returns 0 while
2611 # an option was parsed, non-zero when the option list is exhausted.
2612 #
2613 # A leading ':' in optstring selects "silent" error reporting: getopts
2614 # does not print a diagnostic, sets the name variable to ':' for a
2615 # missing argument and '?' for an unknown option, and puts the offending
2616 # letter in OPTARG. Otherwise getopts prints a message to STDERR, sets
2617 # the name variable to '?', and unsets OPTARG.
2618 #
2619 # If no [arg ...] words are given, the positional parameters $1..$9 are
2620 # parsed (BATsh stores them as %1..%9; the same first-empty-terminates
2621 # convention used elsewhere in this module applies, so an intentionally
2622 # empty positional parameter is not representable).
2623 #
2624 # All Perl 5.005_03 compatible: substr/index scanning, no regex features
2625 # beyond \A \z, no prototypes, 2-argument state via package variables.
2626 sub _cmd_getopts {
2627 my ($rest) = @_;
2628 $rest = '' unless defined $rest;
2629 $rest =~ s/\A\s+//;
2630 $rest =~ s/\s+\z//;
2631  
2632 # Split off optstring and name; the remainder (if any) are explicit
2633 # args. _parse_args handles quoting/word-splitting consistently with
2634 # the rest of the interpreter.
2635 my @words = _parse_args($rest);
2636 if (@words < 2) {
2637 print STDERR "getopts: usage: getopts optstring name [arg ...]\n";
2638 $LAST_STATUS = 2;
2639 return 2;
2640 }
2641 my $optstring = shift @words;
2642 my $name = shift @words;
2643  
2644 # Argument list: explicit words, else the positional parameters.
2645 my @args;
2646 if (@words) {
2647 @args = @words;
2648 }
2649 else {
2650 for my $n (1 .. 9) {
2651 my $v = BATsh::Env->get("%$n");
2652 $v = BATsh::Env->get("BATSH_ARG$n") unless defined $v && $v ne '';
2653 last unless defined $v && $v ne '';
2654 push @args, $v;
2655 }
2656 }
2657  
2658 # Silent-error mode: a leading ':' in the optstring.
2659 my $silent = 0;
2660 if (index($optstring, ':') == 0) {
2661 $silent = 1;
2662 $optstring = substr($optstring, 1);
2663 }
2664  
2665 # OPTIND is 1-based and defaults to 1. If the caller reset it (or it
2666 # has never been set), restart the intra-argument character offset.
2667 my $optind = BATsh::Env->get('OPTIND');
2668 $optind = 1 unless defined $optind && $optind =~ /\A\d+\z/ && $optind >= 1;
2669 if ($optind != $_GETOPTS_LAST_OPTIND) {
2670 $_GETOPTS_CHARPOS = 0; # fresh loop, or manual OPTIND change
2671 }
2672  
2673 # End of arguments?
2674 if ($optind > scalar(@args)) {
2675 $_GETOPTS_CHARPOS = 0;
2676 BATsh::Env->set('OPTIND', $optind);
2677 $_GETOPTS_LAST_OPTIND = $optind;
2678 $LAST_STATUS = 1;
2679 return 1;
2680 }
2681  
2682 my $cur = $args[$optind - 1];
2683 $cur = '' unless defined $cur;
2684  
2685 # Starting a new argument: must begin with '-' and not be a bare '-'.
2686 if ($_GETOPTS_CHARPOS == 0) {
2687 if (index($cur, '-') != 0 || $cur eq '-') {
2688 # Not an option word: stop (leave OPTIND on it).
2689 BATsh::Env->set('OPTIND', $optind);
2690 $_GETOPTS_LAST_OPTIND = $optind;
2691 $LAST_STATUS = 1;
2692 return 1;
2693 }
2694 if ($cur eq '--') {
2695 # Explicit end of options: consume it and stop.
2696 $optind++;
2697 BATsh::Env->set('OPTIND', $optind);
2698 $_GETOPTS_LAST_OPTIND = $optind;
2699 $_GETOPTS_CHARPOS = 0;
2700 $LAST_STATUS = 1;
2701 return 1;
2702 }
2703 $_GETOPTS_CHARPOS = 1; # skip the leading '-'
2704 }
2705  
2706 my $optchar = substr($cur, $_GETOPTS_CHARPOS, 1);
2707 $_GETOPTS_CHARPOS++;
2708 my $is_last_char = ($_GETOPTS_CHARPOS >= length($cur));
2709  
2710 # Advance OPTIND past $cur once its last option character is consumed.
2711 my $advance = sub {
2712 $optind++;
2713 $_GETOPTS_CHARPOS = 0;
2714 };
2715  
2716 # Look the option character up in the optstring. ':' and '?' are
2717 # never valid option letters.
2718 my $pos = ($optchar eq ':' || $optchar eq '?') ? -1
2719 : index($optstring, $optchar);
2720  
2721 if ($pos < 0) {
2722 # Unknown option.
2723 if ($silent) {
2724 BATsh::Env->set($name, '?');
2725 BATsh::Env->set('OPTARG', $optchar);
2726 }
2727 else {
2728 print STDERR BATsh::MB::dec("getopts: illegal option -- $optchar") . "\n";
2729 BATsh::Env->set($name, '?');
2730 BATsh::Env->set('OPTARG', '');
2731 }
2732 $advance->() if $is_last_char;
2733 BATsh::Env->set('OPTIND', $optind);
2734 $_GETOPTS_LAST_OPTIND = $optind;
2735 $LAST_STATUS = 0;
2736 return 0;
2737 }
2738  
2739 # Does this option take an argument? (a ':' follows it in optstring)
2740 my $needs_arg = (substr($optstring, $pos + 1, 1) eq ':');
2741  
2742 if ($needs_arg) {
2743 if (!$is_last_char) {
2744 # -oVALUE : remainder of the current word is the argument.
2745 BATsh::Env->set('OPTARG', substr($cur, $_GETOPTS_CHARPOS));
2746 BATsh::Env->set($name, $optchar);
2747 $advance->();
2748 }
2749 else {
2750 # -o VALUE : the next word is the argument.
2751 if ($optind + 1 > scalar(@args)) {
2752 # Missing argument.
2753 $advance->();
2754 if ($silent) {
2755 BATsh::Env->set($name, ':');
2756 BATsh::Env->set('OPTARG', $optchar);
2757 }
2758 else {
2759 print STDERR BATsh::MB::dec("getopts: option requires an argument -- $optchar") . "\n";
2760 BATsh::Env->set($name, '?');
2761 BATsh::Env->set('OPTARG', '');
2762 }
2763 BATsh::Env->set('OPTIND', $optind);
2764 $_GETOPTS_LAST_OPTIND = $optind;
2765 $LAST_STATUS = 0;
2766 return 0;
2767 }
2768 BATsh::Env->set('OPTARG', $args[$optind]); # 0-based next word
2769 BATsh::Env->set($name, $optchar);
2770 $optind += 2;
2771 $_GETOPTS_CHARPOS = 0;
2772 }
2773 }
2774 else {
2775 # Flag option, no argument. bash unsets OPTARG; we clear it.
2776 BATsh::Env->set($name, $optchar);
2777 BATsh::Env->set('OPTARG', '');
2778 $advance->() if $is_last_char;
2779 }
2780  
2781 BATsh::Env->set('OPTIND', $optind);
2782 $_GETOPTS_LAST_OPTIND = $optind;
2783 $LAST_STATUS = 0;
2784 return 0;
2785 }
2786  
2787 # ----------------------------------------------------------------
2788 # local
2789 # ----------------------------------------------------------------
2790 sub _cmd_local {
2791 my ($rest) = @_;
2792 $rest =~ s/\A\s+//;
2793  
2794 my ($var, $val);
2795 if ($rest =~ /\A([A-Za-z_][A-Za-z0-9_]*)=(.*)\z/s) {
2796 ($var, $val) = ($1, $2);
2797 # Strip surrounding quotes from value
2798 $val =~ s/\A"(.*)"\z/$1/s;
2799 $val =~ s/\A'(.*)'\z/$1/s;
2800 }
2801 elsif ($rest =~ /\A([A-Za-z_][A-Za-z0-9_]*)\s*\z/) {
2802 $var = $1;
2803 $val = BATsh::Env->get($var);
2804 $val = '' unless defined $val;
2805 }
2806 else {
2807 $LAST_STATUS = 0;
2808 return 0;
2809 }
2810  
2811 # Save old value in innermost function scope so it can be restored on return
2812 if (@FUNCTION_STACK) {
2813 my $frame = $FUNCTION_STACK[-1];
2814 # Only save once per variable per frame (first local declaration wins)
2815 unless (exists $frame->{$var}) {
2816 my $old = BATsh::Env->get($var);
2817 $frame->{$var} = defined $old ? $old : undef;
2818 }
2819 }
2820 BATsh::Env->set($var, $val);
2821 $LAST_STATUS = 0;
2822 return 0;
2823 }
2824  
2825 # ----------------------------------------------------------------
2826 # set (sh set options -- minimal implementation)
2827 # ----------------------------------------------------------------
2828 # _sh_set_positional: replace $1..$9 / $@ / $* with a new argument list.
2829 # The interpreter keeps the positional parameters in %1..%9 (mirrored in
2830 # BATSH_ARG1..9 for the legacy CMD-side view) and their space-joined form
2831 # in %*, exactly as a function call and "shift" do, so "set --" reuses
2832 # that representation instead of inventing a second one. OPTIND is
2833 # deliberately NOT reset: bash leaves it alone too, and a script that
2834 # re-parses a fresh list resets it itself.
2835 sub _sh_set_positional {
2836 my ($args_ref) = @_;
2837 my @args = @{$args_ref};
2838 for my $n (1 .. 9) {
2839 my $v = defined $args[$n-1] ? $args[$n-1] : '';
2840 BATsh::Env->set("%$n", $v);
2841 BATsh::Env->set("BATSH_ARG$n", $v);
2842 }
2843 BATsh::Env->set('%*', join(' ', @args));
2844 return 1;
2845 }
2846  
2847 sub _cmd_set_sh {
2848 my ($rest) = @_;
2849 $rest =~ s/\A\s+//;
2850 $rest =~ s/\s+\z//;
2851 # set -e/+e -u/+u -x/+x, combinable (-eux), and set -o/+o NAME
2852 # (errexit / nounset / xtrace). Unknown option letters are accepted
2853 # silently.
2854 #
2855 # POSIX operand handling (v0.09): "set -- [ARG ...]" replaces the
2856 # positional parameters with ARG ... (and clears them when no ARG is
2857 # given), and so does a first word that is not an option, as in
2858 # "set a b c". Until v0.09 every operand form was silently ignored,
2859 # so the common
2860 # set -- -f value ; while getopts f: opt ; do ... done
2861 # idiom saw an empty argument list. Words are split on unquoted
2862 # whitespace and dequoted, so "set -- 'a b' c" sets exactly two
2863 # parameters.
2864 my @words = map { _arr_dequote($_) } _arr_split_words($rest);
2865 my @pos = ();
2866 my $set_pos = 0;
2867 while (@words) {
2868 my $w = shift @words;
2869 if ($w eq '--') {
2870 $set_pos = 1;
2871 @pos = @words;
2872 @words = ();
2873 last;
2874 }
2875  
2876 if ($w =~ /\A([-+])o\z/ && @words) {
2877 my $on = ($1 eq '-') ? 1 : 0;
2878 my $name = lc(shift @words);
2879 if ($name eq 'errexit') { $_OPT_ERREXIT = $on }
2880 elsif ($name eq 'nounset') { $_OPT_NOUNSET = $on }
2881 elsif ($name eq 'xtrace') { $_OPT_XTRACE = $on }
2882 next;
2883 }
2884 if ($w =~ /\A([-+])([a-zA-Z]+)\z/) {
2885 my $on = ($1 eq '-') ? 1 : 0;
2886 for my $ch (split //, $2) {
2887 if ($ch eq 'e') { $_OPT_ERREXIT = $on }
2888 elsif ($ch eq 'u') { $_OPT_NOUNSET = $on }
2889 elsif ($ch eq 'x') { $_OPT_XTRACE = $on }
2890 }
2891 next;
2892 }
2893 # Not an option: this word and every word after it are the new
2894 # positional parameters.
2895 $set_pos = 1;
2896 @pos = ($w, @words);
2897 @words = ();
2898 last;
2899 }
2900 _sh_set_positional(\@pos) if $set_pos;
2901 $LAST_STATUS = 0;
2902 return 0;
2903 }
2904  
2905 # ----------------------------------------------------------------
2906 # shopt -- bash shell option toggle (v0.07, minimal implementation)
2907 #
2908 # Recognised forms:
2909 # shopt -s extglob enable extended pattern matching operators
2910 # ?(...) *(...) +(...) @(...) !(...) in case
2911 # patterns and in ${VAR#pat}/${VAR%pat}/... patterns
2912 # shopt -u extglob disable it (the bash default)
2913 # shopt -p extglob print "shopt -s extglob" or "shopt -u extglob"
2914 # shopt extglob print "extglob on" / "extglob off"
2915 # shopt print the state of all known options
2916 #
2917 # Only "extglob" is modelled; any other option name is accepted silently
2918 # (queried as "off") so scripts that probe unrelated options do not abort.
2919 # ----------------------------------------------------------------
2920 sub _cmd_shopt {
2921 my ($rest) = @_;
2922 $rest =~ s/\A\s+//; $rest =~ s/\s+\z//;
2923 my @words = split /\s+/, $rest;
2924 if (!@words) {
2925 print "extglob " . ($_OPT_EXTGLOB ? 'on' : 'off') . "\n";
2926 $LAST_STATUS = 0;
2927 return 0;
2928 }
2929 my $mode = ''; # '-s' / '-u' / '-p' / '' (bare query)
2930 if ($words[0] =~ /\A-[sup]\z/) { $mode = shift(@words) }
2931 if (!@words) {
2932 # "shopt -p" / "shopt -s" / "shopt -u" with no names: report/no-op
2933 if ($mode eq '-p') {
2934 print 'shopt -' . ($_OPT_EXTGLOB ? 's' : 'u') . " extglob\n";
2935 }
2936 $LAST_STATUS = 0;
2937 return 0;
2938 }
2939 my $status = 0;
2940 for my $name (@words) {
2941 my $lc_name = lc($name);
2942 if ($lc_name ne 'extglob') {
2943 # Unknown option name: treated as always-off, matching bash's
2944 # exit-status-1-on-unknown-name behaviour without aborting.
2945 if ($mode eq '') { print "$name off\n" }
2946 $status = 1;
2947 next;
2948 }
2949 if ($mode eq '-s') { $_OPT_EXTGLOB = 1 }
2950 elsif ($mode eq '-u') { $_OPT_EXTGLOB = 0 }
2951 elsif ($mode eq '-p') { print 'shopt -' . ($_OPT_EXTGLOB ? 's' : 'u') . " extglob\n" }
2952 else { print "extglob " . ($_OPT_EXTGLOB ? 'on' : 'off') . "\n" }
2953 }
2954 $LAST_STATUS = $status;
2955 return $status;
2956 }
2957  
2958 # ----------------------------------------------------------------
2959 # alias / unalias (v0.07, minimal implementation)
2960 #
2961 # alias list all aliases as alias NAME='VALUE'
2962 # alias NAME print one alias, or an error if not set
2963 # alias NAME=VALUE ... define one or more aliases (quote-aware)
2964 # unalias NAME ... remove one or more aliases
2965 # unalias -a remove all aliases
2966 # ----------------------------------------------------------------
2967 sub _cmd_alias {
2968 my ($rest) = @_;
2969 $rest = '' unless defined $rest;
2970 $rest =~ s/\A\s+//; $rest =~ s/\s+\z//;
2971 if ($rest eq '') {
2972 for my $name (sort keys %_SH_ALIAS) {
2973 print "alias $name='" . $_SH_ALIAS{$name} . "'\n";
2974 }
2975 $LAST_STATUS = 0;
2976 return 0;
2977 }
2978 my @tok = _arr_split_words($rest);
2979 my $status = 0;
2980 for my $t (@tok) {
2981 if ($t =~ /\A([A-Za-z_][A-Za-z0-9_.:-]*)=(.*)\z/s) {
2982 my ($name, $val) = ($1, $2);
2983 $_SH_ALIAS{$name} = _arr_dequote($val);
2984 }
2985 elsif ($t =~ /\A([A-Za-z_][A-Za-z0-9_.:-]*)\z/) {
2986 my $name = $1;
2987 if (exists $_SH_ALIAS{$name}) {
2988 print "alias $name='" . $_SH_ALIAS{$name} . "'\n";
2989 }
2990 else {
2991 print STDERR "sh: alias: $name: not found\n";
2992 $status = 1;
2993 }
2994 }
2995 }
2996 $LAST_STATUS = $status;
2997 return $status;
2998 }
2999  
3000 sub _cmd_unalias {
3001 my ($rest) = @_;
3002 $rest = '' unless defined $rest;
3003 $rest =~ s/\A\s+//; $rest =~ s/\s+\z//;
3004 if ($rest eq '-a') { %_SH_ALIAS = (); $LAST_STATUS = 0; return 0 }
3005 my $status = 0;
3006 for my $name (split /\s+/, $rest) {
3007 next if $name eq '';
3008 if (exists $_SH_ALIAS{$name}) { delete $_SH_ALIAS{$name} }
3009 else { print STDERR "sh: unalias: $name: not found\n"; $status = 1 }
3010 }
3011 $LAST_STATUS = $status;
3012 return $status;
3013 }
3014  
3015 # _alias_expand_line: replace a leading alias name with its stored text.
3016 # See the call site in _exec_line() for the chaining / loop-guard notes.
3017 sub _alias_expand_line {
3018 my ($line) = @_;
3019 return $line unless %_SH_ALIAS;
3020 my %seen;
3021 my $out = $line;
3022 my $guard = 0;
3023 while ($guard < 20) {
3024 $guard++;
3025 last unless $out =~ /\A(\s*)(\S+)(.*)\z/s;
3026 my ($lead, $w0, $tail) = ($1, $2, $3);
3027 last unless exists $_SH_ALIAS{$w0};
3028 last if $seen{$w0};
3029 $seen{$w0} = 1;
3030 $out = $lead . $_SH_ALIAS{$w0} . $tail;
3031 }
3032 return $out;
3033 }
3034  
3035 # ----------------------------------------------------------------
3036 # reset_sh_options: restore default shell options. Called by BATsh.pm
3037 # at the start of each top-level run so one script's "set -e" does not
3038 # leak into the next. Call as a plain function.
3039 # ----------------------------------------------------------------
3040 sub reset_sh_options {
3041 $_OPT_ERREXIT = 0;
3042 $_OPT_NOUNSET = 0;
3043 $_OPT_XTRACE = 0;
3044 $_OPT_EXTGLOB = 0;
3045 $_ERREXIT_HOLD = 0;
3046 $_ERREXIT_DONE = 0;
3047 # getopts loop state (v0.07): a fresh top-level run restarts option
3048 # parsing from the first argument, so one script's half-finished
3049 # getopts loop cannot leak its position into the next run.
3050 $_GETOPTS_CHARPOS = 0;
3051 $_GETOPTS_LAST_OPTIND = 0;
3052 # Variable attributes (v0.08) are script-scoped, like the options
3053 # above: a fresh top-level run starts with no readonly / integer
3054 # markings so one script's "readonly X" cannot leak into the next.
3055 %_SH_READONLY = ();
3056 %_SH_INTATTR = ();
3057 return 0;
3058 }
3059  
3060 # ----------------------------------------------------------------
3061 # _errexit_check: under set -e, a failing simple command terminates the
3062 # script with its status. Suppressed while $_ERREXIT_HOLD > 0 (an if/
3063 # while/until condition, or a non-final member of a && / || list) and
3064 # when a control transfer (exit/break/continue/return) is already active.
3065 # ----------------------------------------------------------------
3066 sub _errexit_check {
3067 my ($rc) = @_;
3068 return $rc unless $_OPT_ERREXIT;
3069 return $rc if $_ERREXIT_HOLD;
3070 return $rc unless defined $rc && $rc =~ /\A-?\d+\z/ && $rc != 0;
3071 return $rc if defined $_EXIT_CODE || $_BREAK || $_CONTINUE || $_RETURN;
3072 $_EXIT_CODE = $rc;
3073 $LAST_STATUS = $rc;
3074 return $rc;
3075 }
3076  
3077 # ----------------------------------------------------------------
3078 # _nounset_hit: under set -u, expanding an unset variable is an error
3079 # that terminates the script with status 1 (bash prints the message and
3080 # aborts; here the current command still completes with '' before the
3081 # script stops -- see BUGS AND LIMITATIONS). A noop while -u is off.
3082 # ----------------------------------------------------------------
3083 sub _nounset_hit {
3084 my ($name) = @_;
3085 return 0 unless $_OPT_NOUNSET;
3086 return 0 if defined $_EXIT_CODE; # report only the first hit
3087 warn "sh: $name: unbound variable\n";
3088 $_EXIT_CODE = 1;
3089 $LAST_STATUS = 1;
3090 return 1;
3091 }
3092  
3093 # ----------------------------------------------------------------
3094 # source / .
3095 # ----------------------------------------------------------------
3096 sub _cmd_source {
3097 my ($class, $rest, $opts_ref) = @_;
3098 $rest =~ s/\A\s+//;
3099 $rest =~ s/\s+\z//;
3100 if (defined $opts_ref->{'_batsh'}) {
3101 eval { $opts_ref->{'_batsh'}->source_file($rest) };
3102 if ($@) { print STDERR "source: $rest: $@\n"; return 1 }
3103 }
3104 return 0;
3105 }
3106  
3107 # ----------------------------------------------------------------
3108 # test / [ ]
3109 # ----------------------------------------------------------------
3110 sub _cmd_test {
3111 my ($rest) = @_;
3112 $rest =~ s/\A\s+//;
3113 $rest =~ s/\s*\]\s*\z//; # strip trailing ]
3114 my $result = _eval_test($rest);
3115 $LAST_STATUS = $result ? 0 : 1;
3116 return $LAST_STATUS;
3117 }
3118  
3119 sub _eval_test {
3120 my ($expr) = @_;
3121 $expr =~ s/\A\s+//;
3122 $expr =~ s/\s+\z//;
3123  
3124 # Compound: -a (AND), -o (OR)
3125 if ($expr =~ /^(.*)\s+-a\s+(.*)$/) {
3126 return _eval_test($1) && _eval_test($2);
3127 }
3128 if ($expr =~ /^(.*)\s+-o\s+(.*)$/) {
3129 return _eval_test($1) || _eval_test($2);
3130 }
3131 # Negation
3132 if ($expr =~ /^!\s+(.*)$/) {
3133 return !_eval_test($1);
3134 }
3135  
3136 # File tests
3137 if ($expr =~ /\A(-[a-z])\s+(.+)\z/) {
3138 my ($op, $path) = ($1, $2);
3139 # Quote removal (which is also what turns a backslash that came
3140 # out of an expansion back into a literal one) follows the same
3141 # rules as for command words: test compares its operands
3142 # literally, so a half-stripped "C:\dir"/sub would never name
3143 # an existing file.
3144 $path = _arr_dequote($path);
3145 $path = BATsh::MB::dec($path);
3146 if ($op eq '-e') { return -e $path ? 1 : 0 }
3147 if ($op eq '-f') { return -f $path ? 1 : 0 }
3148 if ($op eq '-d') { return -d $path ? 1 : 0 }
3149 if ($op eq '-r') { return -r $path ? 1 : 0 }
3150 if ($op eq '-w') { return -w $path ? 1 : 0 }
3151 if ($op eq '-x') { return -x $path ? 1 : 0 }
3152 if ($op eq '-s') { return (-s $path) ? 1 : 0 }
3153 if ($op eq '-z') { my $s = -s $path; return (!defined $s || $s == 0) ? 1 : 0 }
3154 if ($op eq '-n') { return (length($path) > 0) ? 1 : 0 }
3155 if ($op eq '-L') { return -l $path ? 1 : 0 }
3156 }
3157  
3158 # String comparisons: = == != < >
3159 if ($expr =~ /\A(.+?)\s+(=|==|!=|<|>)\s+(.+)\z/) {
3160 my ($a, $op, $b) = ($1, $2, $3);
3161 $a = _arr_dequote($a);
3162 $b = _arr_dequote($b);
3163 if ($op eq '=' || $op eq '==') { return ($a eq $b) ? 1 : 0 }
3164 if ($op eq '!=') { return ($a ne $b) ? 1 : 0 }
3165 if ($op eq '<') { return ($a lt $b) ? 1 : 0 }
3166 if ($op eq '>') { return ($a gt $b) ? 1 : 0 }
3167 }
3168  
3169 # Integer comparisons: -eq -ne -lt -le -gt -ge
3170 if ($expr =~ /\A(.+?)\s+(-eq|-ne|-lt|-le|-gt|-ge)\s+(.+)\z/) {
3171 my ($a, $op, $b) = ($1, $2, $3);
3172 $a = _arr_dequote($a);
3173 $b = _arr_dequote($b);
3174 $a = int($a) if $a =~ /\A-?\d+\z/;
3175 $b = int($b) if $b =~ /\A-?\d+\z/;
3176 if ($op eq '-eq') { return ($a == $b) ? 1 : 0 }
3177 if ($op eq '-ne') { return ($a != $b) ? 1 : 0 }
3178 if ($op eq '-lt') { return ($a < $b) ? 1 : 0 }
3179 if ($op eq '-le') { return ($a <= $b) ? 1 : 0 }
3180 if ($op eq '-gt') { return ($a > $b) ? 1 : 0 }
3181 if ($op eq '-ge') { return ($a >= $b) ? 1 : 0 }
3182 }
3183  
3184 # -n string (non-empty)
3185 if ($expr =~ /\A-n\s+(.+)\z/) {
3186 my $s = _arr_dequote($1);
3187 return length($s) > 0 ? 1 : 0;
3188 }
3189 # -z string (empty)
3190 if ($expr =~ /\A-z\s+(.+)\z/) {
3191 my $s = _arr_dequote($1);
3192 return length($s) == 0 ? 1 : 0;
3193 }
3194  
3195 # bare string: true if non-empty
3196 $expr = _arr_dequote($expr);
3197 return (length($expr) > 0 && $expr ne '0') ? 1 : 0;
3198 }
3199  
3200 # ----------------------------------------------------------------
3201 # if/then/else/elif/fi parser
3202 # ----------------------------------------------------------------
3203 sub _parse_if {
3204 my ($class, $lines_ref, $start, $opts_ref) = @_;
3205 my @lines = @{$lines_ref};
3206 my $i = $start;
3207  
3208 # Collect: if cond; then ... [elif cond; then ...] [else ...] fi
3209 # Build a structure: [ ['cond_lines'], ['body_lines'] ] ...
3210 my @branches = (); # [ [$cond_lines], [$body_lines] ]
3211 my $else_body = undef;
3212  
3213 # First line: if cond; then
3214 my $if_line = $lines[$i]; $i++;
3215 $if_line =~ s/\r?\n\z//; $if_line =~ s/\A\s+//;
3216  
3217 # Fully-inline form on ONE physical line:
3218 # if COND; then BODY... [elif COND; then BODY...] [else BODY...]; fi
3219 # Detected by a bare "fi" appearing as a top-level ';' segment. The
3220 # line is expanded into the logical-line shape the multi-line block
3221 # collector below already understands (with then/do/else peeled onto
3222 # their own lines), then re-parsed; this correctly handles elif and
3223 # else, which the previous narrow single-line regex silently dropped.
3224 if (_inline_has_terminator($if_line, 'fi')) {
3225 my @work = _inline_expand($if_line);
3226 my ($st) = _parse_if($class, \@work, 0, $opts_ref);
3227 return ($st, $i);
3228 }
3229  
3230 # Extract condition (after 'if', before 'then' or ';')
3231 my $cond_str = $if_line;
3232 $cond_str =~ s/\Aif\s+//i;
3233  
3234 $cond_str =~ s/\s*;\s*then\s*\z//i;
3235 $cond_str =~ s/\s+then\s*\z//i;
3236  
3237 my @cond_lines = ($cond_str);
3238 my @body_lines = ();
3239 my $in_else = 0; # collecting the else-branch body
3240 # Nested if/fi depth: a nested "if ... fi" inside a branch body (on
3241 # its own lines or written inline) must not have its "fi"/"elif"/
3242 # "else" mistaken for the outer if's. Only the depth-1 keywords are
3243 # the outer if's; deeper ones travel with the body and are re-parsed
3244 # when the body runs.
3245 my $depth = 1;
3246  
3247 while ($i <= $#lines) {
3248 my $l = $lines[$i]; $i++;
3249 $l =~ s/\r?\n\z//;
3250 my $ls = $l; $ls =~ s/\A\s+//;
3251 my $lc_first = lc( ($ls =~ /\A(\S+)/) ? $1 : '' );
3252  
3253 if ($depth == 1 && $lc_first eq 'fi') {
3254 push @branches, [ [@cond_lines], [@body_lines] ] unless $in_else;
3255 $else_body = [@body_lines] if $in_else;
3256 last;
3257 }
3258 elsif ($depth == 1 && !$in_else && $lc_first eq 'elif') {
3259 push @branches, [ [@cond_lines], [@body_lines] ];
3260 $cond_str = $ls;
3261 $cond_str =~ s/\Aelif\s+//i;
3262 $cond_str =~ s/\s*;\s*then\s*\z//i;
3263 $cond_str =~ s/\s+then\s*\z//i;
3264 @cond_lines = ($cond_str);
3265 @body_lines = ();
3266 }
3267 elsif ($depth == 1 && !$in_else && $lc_first eq 'else') {
3268 push @branches, [ [@cond_lines], [@body_lines] ];
3269 @body_lines = ();
3270 $in_else = 1;
3271 }
3272 elsif ($depth == 1 && $lc_first eq 'then') {
3273 # 'then' on its own line: continue collecting body
3274 next;
3275 }
3276 else {
3277 push @body_lines, $l;
3278 $depth += _if_depth_delta($l);
3279 }
3280 }
3281  
3282 # Evaluate branches
3283 my $status = 0;
3284 my $executed = 0;
3285 for my $branch (@branches) {
3286 my ($cond_ref, $body_ref) = @{$branch};
3287 $_ERREXIT_HOLD++;
3288 my $cond_status = _run_lines($class, $cond_ref, $opts_ref);
3289 $_ERREXIT_HOLD--;
3290 if ($cond_status == 0) {
3291 $status = _run_lines($class, $body_ref, $opts_ref);
3292 $executed = 1;
3293 last;
3294 }
3295 }
3296 if (!$executed && defined $else_body) {
3297 $status = _run_lines($class, $else_body, $opts_ref);
3298 }
3299  
3300 return ($status, $i);
3301 }
3302  
3303 # ----------------------------------------------------------------
3304 # for VAR in list; do ... done
3305 # ----------------------------------------------------------------
3306 sub _parse_for {
3307 my ($class, $lines_ref, $start, $opts_ref) = @_;
3308 my @lines = @{$lines_ref};
3309 my $i = $start;
3310  
3311 my $for_line = $lines[$i]; $i++;
3312 $for_line =~ s/\r?\n\z//; $for_line =~ s/\A\s+//;
3313  
3314 # for VAR in LIST [; do [BODY [; done]]]
3315 #
3316 # The header may stand alone (do/done on following lines) or carry an
3317 # inline "; do ... ; done" tail all on one physical line. The inline
3318 # form is detected first; ";do" is matched with \b after "do" so that a
3319 # "; done" terminator is never mistaken for the "do" keyword.
3320 my ($var, $list_str) = ('', '');
3321 my $inline_body; # defined when the header has an inline "do" tail
3322 my $inline_closed = 0; # true when that tail also held the "done"
3323 if ($for_line =~ /\Afor\s+([A-Za-z_][A-Za-z0-9_]*)\s+in\s+(.*?)\s*;\s*do\b\s*(.*)\z/is) {
3324 my $tail;
3325 ($var, $list_str, $tail) = ($1, $2, $3);
3326 $tail =~ s/\s+\z//;
3327 if ($tail eq '') {
3328 $inline_body = undef; # "for ... ; do" -> body follows
3329 }
3330 elsif ($tail =~ /\A(.*);\s*done\b\s*\z/s) {
3331 $inline_body = $1; $inline_closed = 1; # fully inline; greedy = last done
3332 }
3333 elsif ($tail eq 'done') {
3334 $inline_body = ''; $inline_closed = 1; # empty inline body
3335 }
3336 else {
3337 $inline_body = $tail; # "for ... ; do BODY" (done later)
3338 }
3339 }
3340 elsif ($for_line =~ /\Afor\s+([A-Za-z_][A-Za-z0-9_]*)\s+in\s+(.*?)\s*\z/i) {
3341 ($var, $list_str) = ($1, $2); # header only; do/done on later lines
3342 }
3343  
3344 # Collect body until 'done' (skipped when the tail already closed the loop)
3345 my @body = ();
3346 if (defined $inline_body) {
3347 push @body, $inline_body unless $inline_body eq '';
3348 }
3349 if (!$inline_closed) {
3350 my $depth = 1;
3351 while ($i <= $#lines) {
3352 my $l = $lines[$i]; $i++;
3353 $l =~ s/\r?\n\z//;
3354 my $ls = $l; $ls =~ s/\A\s+//;
3355 my $lc_f = lc( ($ls =~ /\A(\S+)/) ? $1 : '' );
3356 if ($lc_f eq 'for' || $lc_f eq 'while' || $lc_f eq 'until') { $depth++ }
3357 if ($lc_f eq 'done') { $depth--; last if $depth == 0 }
3358 push @body, $l unless ($lc_f eq 'do' && $depth == 1);
3359 }
3360 }
3361  
3362 # Expand list items. _expand_word_list resolves variables and command
3363 # substitutions, applies filename globbing to unquoted glob words, and
3364 # expands a whole-word ${arr[@]} / ${arr[*]} reference (quoted or not) to
3365 # one item per array element.
3366 my @items = _expand_word_list($class, $list_str);
3367 my $status = 0;
3368 for my $val (@items) {
3369 BATsh::Env->set($var, $val);
3370 $_BREAK = 0; $_CONTINUE = 0;
3371 $status = _run_lines($class, \@body, $opts_ref);
3372 last if $_BREAK || defined $_EXIT_CODE;
3373 }
3374 $_BREAK = 0;
3375  
3376 return ($status, $i);
3377 }
3378  
3379 # ----------------------------------------------------------------
3380 # select VAR in LIST ; do ... done (v0.07)
3381 #
3382 # Prints a numbered menu of LIST (one item per line, to STDERR), prompts
3383 # with $PS3 (default "#? "), and reads one line from STDIN into REPLY:
3384 # - a number in range 1..#items sets VAR to that item and runs BODY
3385 # - anything else (including a blank line) sets VAR to '' and still
3386 # runs BODY, matching bash (the menu is then reprinted next
3387 # iteration)
3388 # - end of input (STDIN closed) ends the loop, as does break
3389 # There is no multi-column menu layout (bash chooses columns based on
3390 # terminal width and item count); every item is printed on its own line.
3391 # ----------------------------------------------------------------
3392 sub _parse_select {
3393 my ($class, $lines_ref, $start, $opts_ref) = @_;
3394 my @lines = @{$lines_ref};
3395 my $i = $start;
3396  
3397 my $sel_line = $lines[$i]; $i++;
3398 $sel_line =~ s/\r?\n\z//; $sel_line =~ s/\A\s+//;
3399  
3400 my ($var, $list_str) = ('', '');
3401 my $inline_body;
3402 my $inline_closed = 0;
3403 if ($sel_line =~ /\Aselect\s+([A-Za-z_][A-Za-z0-9_]*)\s+in\s+(.*?)\s*;\s*do\b\s*(.*)\z/is) {
3404 my $tail;
3405 ($var, $list_str, $tail) = ($1, $2, $3);
3406 $tail =~ s/\s+\z//;
3407 if ($tail eq '') { $inline_body = undef }
3408 elsif ($tail =~ /\A(.*);\s*done\b\s*\z/s) { $inline_body = $1; $inline_closed = 1 }
3409 elsif ($tail eq 'done') { $inline_body = ''; $inline_closed = 1 }
3410 else { $inline_body = $tail }
3411 }
3412 elsif ($sel_line =~ /\Aselect\s+([A-Za-z_][A-Za-z0-9_]*)\s+in\s+(.*?)\s*\z/i) {
3413 ($var, $list_str) = ($1, $2);
3414 }
3415 elsif ($sel_line =~ /\Aselect\s+([A-Za-z_][A-Za-z0-9_]*)\s*\z/i) {
3416 ($var, $list_str) = ($1, '"$@"'); # "select VAR" alone: positional params
3417 }
3418 else {
3419 return (0, $i); # malformed header: nothing to do
3420 }
3421  
3422 my @body = ();
3423 if (defined $inline_body) {
3424 push @body, $inline_body unless $inline_body eq '';
3425 }
3426 if (!$inline_closed) {
3427 my $depth = 1;
3428 while ($i <= $#lines) {
3429 my $l = $lines[$i]; $i++;
3430 $l =~ s/\r?\n\z//;
3431 my $ls = $l; $ls =~ s/\A\s+//;
3432 my $lc_f = lc( ($ls =~ /\A(\S+)/) ? $1 : '' );
3433 if ($lc_f eq 'for' || $lc_f eq 'while' || $lc_f eq 'until' || $lc_f eq 'select') { $depth++ }
3434 if ($lc_f eq 'done') { $depth--; last if $depth == 0 }
3435 push @body, $l unless ($lc_f eq 'do' && $depth == 1);
3436 }
3437 }
3438  
3439 my @items = _expand_word_list($class, $list_str);
3440 my $status = 0;
3441 return ($status, $i) unless @items;
3442  
3443 my $ps3 = BATsh::Env->get('PS3');
3444 $ps3 = '#? ' unless defined $ps3 && $ps3 ne '';
3445  
3446 my $max_iter = 100_000; # safety guard, mirrors _parse_while
3447 while ($max_iter-- > 0) {
3448 last if defined $_EXIT_CODE;
3449 for my $idx (0 .. $#items) {
3450 print STDERR ($idx + 1) . ') ' . $items[$idx] . "\n";
3451 }
3452 print STDERR BATsh::MB::dec($ps3);
3453 my $answer = <STDIN>;
3454 last unless defined $answer; # EOF on STDIN ends the loop
3455 $answer =~ s/\r?\n\z//;
3456 BATsh::Env->set('REPLY', BATsh::MB::enc($answer));
3457 if ($answer =~ /\A[0-9]+\z/ && $answer >= 1 && $answer <= scalar(@items)) {
3458 BATsh::Env->set($var, $items[$answer - 1]);
3459 }
3460 else {
3461 BATsh::Env->set($var, '');
3462 }
3463 $_BREAK = 0; $_CONTINUE = 0;
3464 $status = _run_lines($class, \@body, $opts_ref);
3465 last if $_BREAK || defined $_EXIT_CODE;
3466 }
3467 $_BREAK = 0;
3468  
3469 return ($status, $i);
3470 }
3471  
3472 # ----------------------------------------------------------------
3473 # while/until condition; do ... done
3474 # ----------------------------------------------------------------
3475 sub _parse_while {
3476 my ($class, $lines_ref, $start, $opts_ref) = @_;
3477 my @lines = @{$lines_ref};
3478 my $i = $start;
3479  
3480 my $while_line = $lines[$i]; $i++;
3481 $while_line =~ s/\r?\n\z//; $while_line =~ s/\A\s+//;
3482  
3483 my $is_until = ($while_line =~ /\Auntil\s/i) ? 1 : 0;
3484  
3485 # Extract condition, supporting an inline "COND; do BODY; done [REDIR]" form
3486 # as well as the multi-line header. As in _parse_for, ";do" is matched with
3487 # \b after "do" so that a "; done" terminator is never taken for "do".
3488 my $rest = $while_line;
3489 $rest =~ s/\A(?:while|until)\s+//i;
3490  
3491 my $cond_str;
3492 my @body = ();
3493 my $done_line = '';
3494 my $inline_body;
3495 my $inline_closed = 0;
3496  
3497 if ($rest =~ /\A(.*?)\s*;\s*do\b\s*(.*)\z/s) {
3498 my $tail;
3499 ($cond_str, $tail) = ($1, $2);
3500 $tail =~ s/\s+\z//;
3501 if ($tail eq '') {
3502 $inline_body = undef; # "while COND; do" -> body follows
3503 }
3504 elsif ($tail =~ /\A(.*);\s*done\b\s*(.*)\z/s) {
3505 $inline_body = $1; # greedy = last "; done"
3506 $inline_closed = 1;
3507 my $dr = $2; $dr =~ s/\A\s+//; $dr =~ s/\s+\z//;
3508 $done_line = ($dr ne '') ? "done $dr" : 'done';
3509 }
3510 elsif ($tail =~ /\Adone\b\s*(.*)\z/s) {
3511 $inline_body = ''; # empty inline body
3512 $inline_closed = 1;
3513 my $dr = $1; $dr =~ s/\A\s+//; $dr =~ s/\s+\z//;
3514 $done_line = ($dr ne '') ? "done $dr" : 'done';
3515 }
3516 else {
3517 $inline_body = $tail; # done on following lines
3518 }
3519 }
3520 else {
3521 $cond_str = $rest; # header only; do/done on later lines
3522 $cond_str =~ s/\s*;\s*do\s*\z//i;
3523 $cond_str =~ s/\s+do\s*\z//i;
3524 }
3525  
3526 # Collect body (skipped when the inline tail already closed the loop)
3527 if (defined $inline_body) {
3528 push @body, $inline_body unless $inline_body eq '';
3529 }
3530 if (!$inline_closed) {
3531 my $depth = 1;
3532 while ($i <= $#lines) {
3533 my $l = $lines[$i]; $i++;
3534 $l =~ s/\r?\n\z//;
3535 my $ls = $l; $ls =~ s/\A\s+//;
3536 my $lc_f = lc( ($ls =~ /\A(\S+)/) ? $1 : '' );
3537 if ($lc_f eq 'for' || $lc_f eq 'while' || $lc_f eq 'until') { $depth++ }
3538 if ($lc_f eq 'done') { $depth--; if ($depth == 0) { $done_line = $ls; last } }
3539 push @body, $l unless ($lc_f eq 'do' && $depth == 1);
3540 }
3541 }
3542  
3543 # Honor an input redirection on the `done' line, e.g.
3544 # while read LINE; do ...; done < FILE
3545 # by reopening STDIN from FILE for the duration of the loop so that the
3546 # loop's `read' built-in consumes the file. Perl 5.005_03 compatible:
3547 # 2-argument open and bareword filehandle duplication.
3548 my $saved_in = 0;
3549 if ($done_line ne '') {
3550 my $done_rest = $done_line;
3551 $done_rest =~ s/\Adone\b\s*//i;
3552 if ($done_rest ne '') {
3553 my ($dc, $rd) = _sh_strip_redirects(_expand($class, $done_rest));
3554 my $in_file;
3555 for my $r (@{$rd}) {
3556 my ($fd, $append, $file) = @{$r};
3557 $in_file = $file if $fd == 0;
3558 }
3559 if (defined $in_file && $in_file ne '') {
3560 if (sysopen(_WH_REDIR_SRC, $in_file, O_RDONLY)) {
3561 if (open(_WH_REDIR_SAVIN, '<&STDIN')) {
3562 if (open(STDIN, '<&_WH_REDIR_SRC')) { $saved_in = 1 }
3563 }
3564 close(_WH_REDIR_SRC);
3565 }
3566 else {
3567 warn "sh: $in_file: $!\n";
3568 }
3569 }
3570 }
3571 }
3572  
3573 my $status = 0;
3574 my $max_iter = 100_000; # safety guard
3575 while ($max_iter-- > 0) {
3576 last if defined $_EXIT_CODE;
3577 $_ERREXIT_HOLD++;
3578 my $cond_status = _run_lines($class, [$cond_str], $opts_ref);
3579 $_ERREXIT_HOLD--;
3580 my $cond_true = ($cond_status == 0);
3581 last if $is_until && $cond_true;
3582 last if !$is_until && !$cond_true;
3583 $_BREAK = 0; $_CONTINUE = 0;
3584 $status = _run_lines($class, \@body, $opts_ref);
3585 last if $_BREAK;
3586 }
3587 $_BREAK = 0;
3588  
3589 if ($saved_in) {
3590 open(STDIN, '<&_WH_REDIR_SAVIN');
3591 close(_WH_REDIR_SAVIN);
3592 }
3593  
3594 return ($status, $i);
3595 }
3596  
3597 # ----------------------------------------------------------------
3598 # case $var in pattern) ... ;; esac
3599 # ----------------------------------------------------------------
3600 sub _parse_case {
3601 my ($class, $lines_ref, $start, $opts_ref) = @_;
3602 my @lines = @{$lines_ref};
3603 my $i = $start;
3604  
3605 my $case_line = $lines[$i]; $i++;
3606 $case_line =~ s/\r?\n\z//; $case_line =~ s/\A\s+//;
3607  
3608 # Header: case WORD in [inline clauses...]
3609 # The clauses (and even esac) may follow inline on the same physical line
3610 # -- e.g. "case $x in a) echo a ;; *) echo other ;; esac" -- or on the
3611 # following lines. $inline_rest captures anything after "in".
3612 my $word = '';
3613 my $inline_rest = '';
3614 if ($case_line =~ /\Acase\s+(.*?)\s+in\b\s*(.*)\z/is) {
3615 $word = _arr_dequote(_expand($class, $1));
3616 $inline_rest = $2;
3617 }
3618 else {
3619 return (0, $i); # malformed header: nothing to do
3620 }
3621  
3622 # Accumulate the clause region (everything between "in" and "esac"),
3623 # stopping as soon as the closing esac is seen. esac is only recognised
3624 # at a clause boundary (start of region, after a ;;/;&/;;& terminator, or
3625 # at the start of a line), so the word "esac" appearing inside a body
3626 # (e.g. echo esac) does not end the construct prematurely.
3627 my $region = '';
3628 my $found = 0;
3629 {
3630 my $pos = _case_top_esac_pos($inline_rest);
3631 if ($pos >= 0) { $region = substr($inline_rest, 0, $pos); $found = 1 }
3632 else { $region = $inline_rest }
3633 }
3634 while (!$found && $i <= $#lines) {
3635 my $l = $lines[$i]; $i++;
3636 $l =~ s/\r?\n\z//;
3637 my $pos = _case_top_esac_pos($l);
3638 if ($pos >= 0) {
3639 $region .= "\n" . substr($l, 0, $pos);
3640 $found = 1;
3641 last;
3642 }
3643 $region .= "\n" . $l;
3644 }
3645  
3646 # Split the region into clauses, then evaluate with fall-through support:
3647 # ;; normal: stop after the first matching clause
3648 # ;& fall through: run the NEXT clause's body unconditionally
3649 # ;;& continue: keep testing the remaining clauses against the word
3650 my @clauses = _case_split_clauses($region);
3651  
3652 my $status = 0;
3653 my $stop = 0; # a ;; was reached after a match -- stop entirely
3654 my $fall = 0; # previous clause ended in ;& -- run this body no matter what
3655 for my $cl (@clauses) {
3656 last if $stop;
3657 my ($ctext, $term) = @{$cl};
3658 next unless $ctext =~ /\S/;
3659  
3660 my ($pattern_str, $body_text) = _case_parse_clause($ctext);
3661 next unless defined $pattern_str; # not a pattern) clause -- skip
3662  
3663 my $run = 0;
3664 if ($fall) {
3665 $run = 1;
3666 $fall = 0;
3667 }
3668 else {
3669 for my $pat (_case_split_patterns($pattern_str)) {
3670 $pat =~ s/\A\s+//; $pat =~ s/\s+\z//;
3671 next if $pat eq '';
3672 if (_match_pattern($word, $pat)) { $run = 1; last }
3673 }
3674 }
3675  
3676 if ($run) {
3677 my @body = split /\n/, $body_text;
3678 $status = _run_lines($class, \@body, $opts_ref);
3679 last if $_BREAK || $_CONTINUE || $_RETURN || defined $_EXIT_CODE;
3680 if ($term eq ';;') { $stop = 1 }
3681 elsif ($term eq ';&') { $fall = 1 } # next body unconditionally
3682 # ';;&' : neither stop nor fall -- keep testing later clauses
3683 }
3684 }
3685  
3686 return ($status, $i);
3687 }
3688  
3689 # ----------------------------------------------------------------
3690 # ( commands ) -- subshell command group with isolated scope (v0.07)
3691 #
3692 # There is no real fork here (this interpreter never forks -- see the
3693 # pipeline / background-job / exec notes elsewhere in this file), so
3694 # isolation is approximated by snapshotting every piece of state a real
3695 # subshell would not leak changes from -- variables, indexed/associative
3696 # arrays, function definitions, aliases, and the working directory --
3697 # running the body, and restoring all of it afterward regardless of how
3698 # the body finished. "exit" inside the group ends only the group (its
3699 # status becomes the group's status); break/continue/return still
3700 # propagate to an enclosing loop/function exactly as bash's ( ... ) does
3701 # NOT contain them.
3702 #
3703 # Both the single-line form "( cmd1; cmd2 )" and the multi-line form
3704 # (bare "(" ending the first line, matching bare ")" ending the last)
3705 # are recognised. A trailing ">" / ">>" / "<" redirection after the
3706 # closing ")" is honoured; other trailing redirections (2>, 2>&1, ...)
3707 # and a trailing "&" are not -- documented as known limitations.
3708 # ----------------------------------------------------------------
3709 sub _parse_subshell {
3710 my ($class, $lines_ref, $start, $opts_ref) = @_;
3711 my @lines = @{$lines_ref};
3712 my $i = $start;
3713  
3714 my $first_line = $lines[$i]; $i++;
3715 $first_line =~ s/\r?\n\z//;
3716 my $stripped = $first_line;
3717 $stripped =~ s/\A\s+//;
3718  
3719 my @body_lines;
3720 my $trailer = '';
3721 my $found_close = 0;
3722  
3723 # Try the single-line form first: a quote-aware paren-depth scan for
3724 # the ')' that matches this line's opening '('.
3725 {
3726 my @c = split //, $stripped;
3727 my $n = scalar @c;
3728 my $in_sq = 0;
3729 my $in_dq = 0;
3730 my $d = 0;
3731 my $close_pos;
3732 for (my $k = 0; $k < $n; $k++) {
3733 my $ch = $c[$k];
3734 if ($in_sq) { $in_sq = 0 if $ch eq "'"; next }
3735 if ($ch eq "'" && !$in_dq) { $in_sq = 1; next }
3736 if ($ch eq '"' && !$in_sq) { $in_dq = !$in_dq; next }
3737 next if $in_sq || $in_dq;
3738 if ($ch eq '(') { $d++ }
3739 elsif ($ch eq ')') { $d--; if ($d == 0) { $close_pos = $k; last } }
3740 }
3741 if (defined $close_pos) {
3742 push @body_lines, substr($stripped, 1, $close_pos - 1);
3743 $trailer = substr($stripped, $close_pos + 1);
3744 $found_close = 1;
3745 }
3746 }
3747  
3748 if (!$found_close) {
3749 # Multi-line form: accumulate lines, counting '(' / ')' globally
3750 # per line (not quote-aware, matching the existing _parse_function
3751 # brace-counter's level of rigor) until the depth returns to 0.
3752 my $accum = substr($stripped, 1);
3753 my $opens = () = ($accum =~ /\(/g);
3754 my $closes = () = ($accum =~ /\)/g);
3755 my $depth = 1 + $opens - $closes;
3756 push @body_lines, $accum if $accum =~ /\S/;
3757 if ($depth <= 0) {
3758 $found_close = 1;
3759 if (@body_lines && $body_lines[-1] =~ /\A(.*)\)([^)]*)\z/s) {
3760 $body_lines[-1] = $1;
3761 $trailer = $2;
3762 }
3763 }
3764 else {
3765 while ($i <= $#lines) {
3766 my $l = $lines[$i]; $i++;
3767 $l =~ s/\r?\n\z//;
3768 my $o = () = ($l =~ /\(/g);
3769 my $c2 = () = ($l =~ /\)/g);
3770 $depth += $o - $c2;
3771 if ($depth <= 0) {
3772 if ($l =~ /\A(.*)\)([^)]*)\z/s) {
3773 push @body_lines, $1 if $1 =~ /\S/;
3774 $trailer = $2;
3775 }
3776 $found_close = 1;
3777 last;
3778 }
3779 push @body_lines, $l;
3780 }
3781 }
3782 }
3783  
3784 my @body;
3785 for my $bl (@body_lines) {
3786 for my $part (split /;/, $bl) {
3787 push @body, $part if $part =~ /\S/;
3788 }
3789 }
3790  
3791 # Trailing "> file" / ">> file" / "< file" on the closing ')' line.
3792 $trailer =~ s/\A\s+//; $trailer =~ s/\s+\z//;
3793 my ($subsh_out_file, $subsh_out_append, $subsh_in_file);
3794 if ($trailer ne '') {
3795 my $texp = _expand($class, $trailer);
3796 # Reuse the main redirection parser so a quoted target ("a b",
3797 # ">name", "cmd|") is read and dequoted exactly as elsewhere.
3798 my @tr_parts = _sh_strip_redirects($texp);
3799 my $tr_redirs = $tr_parts[1];
3800 for my $r (@{$tr_redirs}) {
3801 my ($fd, $app, $file) = @{$r};
3802 next if $file =~ /\A&[12]\z/; # dup forms handled in body
3803 if ($fd == 0) { $subsh_in_file = $file }
3804 elsif ($fd == 1) { $subsh_out_file = $file; $subsh_out_append = $app }
3805 }
3806 }
3807  
3808 my $saved_out = 0;
3809 my $saved_in = 0;
3810 my $redir_failed = 0;
3811 if (defined $subsh_out_file) {
3812 if (sysopen(_SH_SUBSH_DST, BATsh::MB::dec($subsh_out_file),
3813 O_WRONLY | O_CREAT | ($subsh_out_append ? O_APPEND : O_TRUNC),
3814 0666)) {
3815 if (open(_SH_SUBSH_SAVOUT, '>&STDOUT')) {
3816 if (open(STDOUT, '>&_SH_SUBSH_DST')) { $saved_out = 1 }
3817 }
3818 close(_SH_SUBSH_DST);
3819 }
3820 else { warn "sh: $subsh_out_file: $!\n"; $redir_failed = 1 }
3821 }
3822 if (defined $subsh_in_file) {
3823 if (sysopen(_SH_SUBSH_SRC, BATsh::MB::dec($subsh_in_file), O_RDONLY)) {
3824 if (open(_SH_SUBSH_SAVIN, '<&STDIN')) {
3825 if (open(STDIN, '<&_SH_SUBSH_SRC')) { $saved_in = 1 }
3826 }
3827 close(_SH_SUBSH_SRC);
3828 }
3829 else { warn "sh: $subsh_in_file: $!\n"; $redir_failed = 1 }
3830 }
3831  
3832 # A failed redirection aborts the group without running its body -- as
3833 # the shell does for "( cat ) < missing": it reports the error and does
3834 # NOT fall through to read the terminal (which would hang). Restore any
3835 # handle already swapped, then return failure.
3836 if ($redir_failed) {
3837 if ($saved_out) { open(STDOUT, '>&_SH_SUBSH_SAVOUT'); close(_SH_SUBSH_SAVOUT) }
3838 if ($saved_in) { open(STDIN, '<&_SH_SUBSH_SAVIN'); close(_SH_SUBSH_SAVIN) }
3839 $LAST_STATUS = 1;
3840 return (1, $i);
3841 }
3842  
3843 # Snapshot everything the subshell must not leak changes to.
3844 my $env_snap = BATsh::Env->snapshot();
3845 my %arr_snap = %_SH_ARRAY;
3846 my %arrty_snap = %_SH_ARRAY_TYPE;
3847 my %fn_snap = %_SH_FUNCTIONS;
3848 my %alias_snap = %_SH_ALIAS;
3849 my $cwd_snap = defined(&Cwd::cwd) ? Cwd::cwd() : undef;
3850  
3851 $_BREAK = 0; $_CONTINUE = 0;
3852 my $status = _run_lines($class, \@body, $opts_ref);
3853 my $subshell_exit = $_EXIT_CODE; # "exit" inside ( ... ) ends only the group
3854 $_EXIT_CODE = undef;
3855 $status = $subshell_exit if defined $subshell_exit;
3856  
3857 BATsh::Env->restore($env_snap);
3858 %_SH_ARRAY = %arr_snap;
3859 %_SH_ARRAY_TYPE = %arrty_snap;
3860 %_SH_FUNCTIONS = %fn_snap;
3861 %_SH_ALIAS = %alias_snap;
3862 chdir($cwd_snap) if defined $cwd_snap && $cwd_snap ne '';
3863  
3864 if ($saved_out) { open(STDOUT, '>&_SH_SUBSH_SAVOUT'); close(_SH_SUBSH_SAVOUT) }
3865 if ($saved_in) { open(STDIN, '<&_SH_SUBSH_SAVIN'); close(_SH_SUBSH_SAVIN) }
3866  
3867 $LAST_STATUS = $status;
3868 return ($status, $i);
3869 }
3870  
3871 # Locate a clause-boundary "esac" at the top level of $s (outside quotes).
3872 # Returns its character offset, or -1. An esac is only at a clause boundary
3873 # when the preceding non-blank character is a ';', '&', or newline, or it is
3874 # at the very start -- so "echo esac" inside a body does not match.
3875 sub _case_top_esac_pos {
3876 my ($s) = @_;
3877 return -1 unless defined $s && $s ne '';
3878 my @c = split //, $s;
3879 my $n = scalar @c;
3880 my $i = 0; my $sq = 0; my $dq = 0;
3881 while ($i < $n) {
3882 my $ch = $c[$i];
3883 if ($sq) { $sq = 0 if $ch eq "'"; $i++; next }
3884 if ($ch eq "'" && !$dq) { $sq = 1; $i++; next }
3885 if ($ch eq '"') { $dq = !$dq; $i++; next }
3886 if (!$dq && lc(substr($s, $i, 4)) eq 'esac') {
3887 my $after = ($i + 4 < $n) ? substr($s, $i + 4, 1) : '';
3888 my $aok = ($i + 4 >= $n || $after =~ /\s/) ? 1 : 0;
3889 my $j = $i - 1;
3890 $j-- while $j >= 0 && ($c[$j] eq ' ' || $c[$j] eq "\t");
3891 my $bok = ($j < 0 || $c[$j] eq ';' || $c[$j] eq '&'
3892 || $c[$j] eq "\n") ? 1 : 0;
3893 return $i if $aok && $bok;
3894 }
3895 $i++;
3896 }
3897 return -1;
3898 }
3899  
3900 # Split a case region into clauses on the terminators ;;& / ;; / ;& at the
3901 # top level (outside quotes). Returns a list of [clause_text, terminator].
3902 sub _case_split_clauses {
3903 my ($s) = @_;
3904 my @out;
3905 my $cur = '';
3906 my @c = split //, $s;
3907 my $n = scalar @c;
3908 my $i = 0; my $sq = 0; my $dq = 0;
3909 while ($i < $n) {
3910 my $ch = $c[$i];
3911 if ($sq) { $cur .= $ch; $sq = 0 if $ch eq "'"; $i++; next }
3912 if ($ch eq "'" && !$dq) { $sq = 1; $cur .= $ch; $i++; next }
3913 if ($ch eq '"') { $dq = !$dq; $cur .= $ch; $i++; next }
3914 if (!$sq && !$dq) {
3915 if (substr($s, $i, 3) eq ';;&') {
3916 push @out, [$cur, ';;&']; $cur = ''; $i += 3; next;
3917 }
3918 if (substr($s, $i, 2) eq ';;') {
3919 push @out, [$cur, ';;']; $cur = ''; $i += 2; next;
3920 }
3921 if (substr($s, $i, 2) eq ';&') {
3922 push @out, [$cur, ';&']; $cur = ''; $i += 2; next;
3923 }
3924 }
3925 $cur .= $ch; $i++;
3926 }
3927 push @out, [$cur, ';;'] if $cur =~ /\S/;
3928 return @out;
3929 }
3930  
3931 # Parse a clause "pat1|pat2) body" into ($patterns, $body). A leading "("
3932 # is accepted (bash form). The "(" closing the pattern list is the first
3933 # top-level ")" outside quotes and outside a [...] class. Returns
3934 # (undef, undef) when no pattern ")" is present.
3935 sub _case_parse_clause {
3936 my ($s) = @_;
3937 $s =~ s/\A[\s\n]+//;
3938 $s =~ s/\A\(//; # optional leading (
3939 my @c = split //, $s;
3940 my $n = scalar @c;
3941 my $i = 0; my $sq = 0; my $dq = 0; my $cls = 0; my $paren = 0;
3942 my $found = -1;
3943 while ($i < $n) {
3944 my $ch = $c[$i];
3945 if ($sq) { $sq = 0 if $ch eq "'"; $i++; next }
3946 if ($ch eq "'" && !$dq) { $sq = 1; $i++; next }
3947 if ($ch eq '"') { $dq = !$dq; $i++; next }
3948 if (!$sq && !$dq) {
3949 if ($ch eq '[') { $cls = 1 }
3950 elsif ($ch eq ']') { $cls = 0 }
3951 # An extglob group (?(...)/*(.../@(.../!(...)) contributes a
3952 # balanced '(' ... ')' pair inside the pattern text; only a
3953 # ')' at $paren == 0 is the clause terminator. Tracked
3954 # unconditionally, harmless when there is no '(' present.
3955 elsif ($ch eq '(' && !$cls) { $paren++ }
3956 elsif ($ch eq ')' && !$cls) {
3957 if ($paren > 0) { $paren-- }
3958 else { $found = $i; last }
3959 }
3960 }
3961 $i++;
3962 }
3963 return (undef, undef) if $found < 0;
3964 my $patterns = substr($s, 0, $found);
3965 my $body = ($found + 1 <= length($s)) ? substr($s, $found + 1) : '';
3966 return ($patterns, $body);
3967 }
3968  
3969 # Split a pattern list on top-level "|" (outside quotes and [...] classes).
3970 sub _case_split_patterns {
3971 my ($s) = @_;
3972 my @out;
3973 my $cur = '';
3974 my @c = split //, $s;
3975 my $n = scalar @c;
3976 my $i = 0; my $sq = 0; my $dq = 0; my $cls = 0; my $paren = 0;
3977 while ($i < $n) {
3978 my $ch = $c[$i];
3979 if ($sq) { $cur .= $ch; $sq = 0 if $ch eq "'"; $i++; next }
3980 if ($ch eq "'" && !$dq) { $sq = 1; $cur .= $ch; $i++; next }
3981 if ($ch eq '"') { $dq = !$dq; $cur .= $ch; $i++; next }
3982 if (!$sq && !$dq) {
3983 if ($ch eq '[') { $cls = 1 }
3984 elsif ($ch eq ']') { $cls = 0 }
3985 # Parenthesis depth: keeps an extglob group's internal '|'
3986 # (e.g. @(abc|def)) from being mistaken for a pattern
3987 # separator. Tracked unconditionally -- harmless when
3988 # extglob is off, since ordinary patterns rarely contain a
3989 # literal unescaped '('.
3990 elsif ($ch eq '(' && !$cls) { $paren++ }
3991 elsif ($ch eq ')' && !$cls && $paren > 0) { $paren-- }
3992 elsif ($ch eq '|' && !$cls && !$paren) { push @out, $cur; $cur = ''; $i++; next }
3993 }
3994 $cur .= $ch; $i++;
3995 }
3996 push @out, $cur;
3997 return @out;
3998 }
3999  
4000 # Match a shell-glob case pattern against a word. Supports * ? and
4001 # character classes [abc] [a-z] [!abc]/[^abc], plus quoting and backslash
4002 # escapes (a quoted or escaped metacharacter is matched literally).
4003 sub _match_pattern {
4004 my ($word, $pat) = @_;
4005 $word = '' unless defined $word;
4006 my $re = _case_glob_to_re($pat);
4007 return ($word =~ /\A$re\z/) ? 1 : 0;
4008 }
4009  
4010 sub _case_glob_to_re {
4011 my ($pat) = @_;
4012 $pat = '' unless defined $pat;
4013 my $re = '';
4014 my @c = split //, $pat;
4015 my $n = scalar @c;
4016 my $i = 0;
4017 while ($i < $n) {
4018 my $ch = $c[$i];
4019 if ($_OPT_EXTGLOB && $ch =~ /[?*+\@!]/ && $i+1 < $n && $c[$i+1] eq '(') {
4020 my @eg = _extglob_scan(\@c, $i, \&_case_glob_to_re);
4021 if (@eg) { $re .= $eg[1]; $i = $eg[0]; next }
4022 }
4023 if ($ch eq "'") { # literal single-quoted run
4024 $i++;
4025 while ($i < $n && $c[$i] ne "'") { $re .= quotemeta($c[$i]); $i++ }
4026 $i++; next;
4027 }
4028 if ($ch eq '"') { # literal double-quoted run
4029 $i++;
4030 while ($i < $n && $c[$i] ne '"') {
4031 if ($c[$i] eq '\\' && $i + 1 < $n) {
4032 $i++; $re .= quotemeta($c[$i]); $i++; next;
4033 }
4034 $re .= quotemeta($c[$i]); $i++;
4035 }
4036 $i++; next;
4037 }
4038 if ($ch eq '\\') { # escaped literal
4039 $i++; $re .= quotemeta($c[$i]) if $i < $n; $i++; next;
4040 }
4041 if ($ch eq '*') { $re .= '.*'; $i++; next }
4042 if ($ch eq '?') { $re .= '.'; $i++; next }
4043 if ($ch eq '[') { # character class
4044 my $j = $i + 1;
4045 my $neg = 0;
4046 if ($j < $n && ($c[$j] eq '!' || $c[$j] eq '^')) { $neg = 1; $j++ }
4047 my $body = '';
4048 if ($j < $n && $c[$j] eq ']') { $body .= '\\]'; $j++ } # leading ] literal
4049 while ($j < $n && $c[$j] ne ']') {
4050 my $cc = $c[$j];
4051 if ($cc eq '\\' && $j + 1 < $n) {
4052 $body .= '\\' . $c[$j + 1]; $j += 2; next;
4053 }
4054 if ($cc eq '\\' || $cc eq '^' || $cc eq ']') { $body .= '\\' . $cc }
4055 else { $body .= $cc }
4056 $j++;
4057 }
4058 if ($j < $n && $c[$j] eq ']') {
4059 $re .= '[' . ($neg ? '^' : '') . $body . ']';
4060 $i = $j + 1; next;
4061 }
4062 $re .= '\\['; $i++; next; # unterminated [ : literal
4063 }
4064 $re .= quotemeta($ch);
4065 $i++;
4066 }
4067 return $re;
4068 }
4069  
4070 # ----------------------------------------------------------------
4071 # extglob (v0.07): ?(list) *(list) +(list) @(list) !(list) pattern-list
4072 # operators, active only while "shopt -s extglob" is on. Shared by
4073 # _case_glob_to_re() (case patterns) and _glob_to_re() (${VAR%pat} and
4074 # friends). $convert_sub converts one pattern-list alternative (which
4075 # may itself contain nested extglob groups) to a regex fragment.
4076 #
4077 # Returns ($pos_after_close_paren, $regex_fragment), or () when the
4078 # text at $i is not a well-formed extglob group (extglob is then left
4079 # to fall through to its ordinary, literal meaning for that character).
4080 #
4081 # !(list) is approximated as "any run of characters that never forms a
4082 # complete match of one of the alternatives" via a negative lookahead
4083 # repeated per character; this matches the common "exclude these whole
4084 # patterns" usage (e.g. !(*.jpg|*.png)) but, unlike real extglob, is not
4085 # exact when !(...) is combined with more pattern after it in the same
4086 # glob -- documented as a known limitation.
4087 # ----------------------------------------------------------------
4088 sub _extglob_scan {
4089 my ($chars_ref, $i, $convert_sub) = @_;
4090 my @c = @{$chars_ref};
4091 my $n = scalar @c;
4092 return () unless $i+1 < $n && $c[$i+1] eq '(';
4093 my $op = $c[$i];
4094 my $depth = 1;
4095 my $j = $i + 2;
4096 my $body = '';
4097 while ($j < $n && $depth > 0) {
4098 my $cc = $c[$j];
4099 if ($cc eq '(') { $depth++; $body .= $cc; $j++ }
4100 elsif ($cc eq ')') { $depth--; $j++; $body .= $cc if $depth > 0 }
4101 elsif ($cc eq '\\' && $j+1 < $n) { $body .= $cc . $c[$j+1]; $j += 2 }
4102 else { $body .= $cc; $j++ }
4103 }
4104 return () if $depth != 0;
4105  
4106 my @alts = _extglob_split_alts($body);
4107 my @re_alts = map { $convert_sub->($_) } @alts;
4108 my $inner = '(?:' . join('|', @re_alts) . ')';
4109 my $frag;
4110 if ($op eq '?') { $frag = $inner . '?' }
4111 elsif ($op eq '*') { $frag = $inner . '*' }
4112 elsif ($op eq '+') { $frag = $inner . '+' }
4113 elsif ($op eq '@') { $frag = $inner }
4114 elsif ($op eq '!') { $frag = '(?:(?!' . $inner . ').)*' }
4115 else { return () }
4116 return ($j, $frag);
4117 }
4118  
4119 # _extglob_split_alts: split an extglob pattern-list body on top-level
4120 # '|' (respecting nested parens and backslash escapes).
4121 sub _extglob_split_alts {
4122 my ($body) = @_;
4123 my @out;
4124 my $cur = '';
4125 my @c = split //, $body;
4126 my $n = scalar @c;
4127 my $i = 0;
4128 my $depth = 0;
4129 while ($i < $n) {
4130 my $ch = $c[$i];
4131 if ($ch eq '\\' && $i+1 < $n) { $cur .= $ch . $c[$i+1]; $i += 2; next }
4132 if ($ch eq '(') { $depth++; $cur .= $ch; $i++; next }
4133 if ($ch eq ')') { $depth--; $cur .= $ch; $i++; next }
4134 if ($ch eq '|' && $depth == 0) { push @out, $cur; $cur = ''; $i++; next }
4135 $cur .= $ch; $i++;
4136 }
4137 push @out, $cur;
4138 return @out;
4139 }
4140  
4141 # ----------------------------------------------------------------
4142 # External command
4143 # ----------------------------------------------------------------
4144 # ----------------------------------------------------------------
4145 # _split_sh_pipe: split a SH command line on bare | characters,
4146 # respecting single-quoted, double-quoted, and $(...) regions.
4147 # Returns a list of segment strings; length 1 means no pipe found.
4148 # ----------------------------------------------------------------
4149 # _split_sh_compound: split a SH line on bare && / || / ;
4150 # Returns list of { op => '', cmd => '...' } hashrefs.
4151 # Length 1 means no compound operator found.
4152 # Respects single-quotes, double-quotes, and $(...) nesting.
4153 # ----------------------------------------------------------------
4154 # _sh_strip_redirects: parse SH-style redirections from a command line.
4155 #
4156 # Recognized forms (processed right-to-left, last one wins per fd):
4157 # cmd > file stdout overwrite
4158 # cmd >> file stdout append
4159 # cmd < file stdin
4160 # cmd 2> file stderr overwrite
4161 # cmd 2>> file stderr append
4162 # cmd 2>&1 stderr to stdout (recorded as fd=2, file='&1')
4163 # cmd 1>&2 stdout to stderr (recorded as fd=1, file='&2')
4164 #
4165 # Returns ($clean_cmd, \@redirs) where each redir is [fd, append, file].
4166 # Parsing respects single-quotes, double-quotes, and backslash escapes.
4167 # ----------------------------------------------------------------
4168 # ----------------------------------------------------------------
4169 # _sh_strip_herestring: detect an unquoted "<<< word" (here-string) on
4170 # an already variable-expanded line. Returns ($line_without_it,
4171 # $dequoted_word) when found, or ($line, undef) otherwise. Only the
4172 # first occurrence on the line is honoured (one here-string per
4173 # command, matching the existing single-here-document limitation).
4174 # ----------------------------------------------------------------
4175 sub _sh_strip_herestring {
4176 my ($line) = @_;
4177 my @c = split //, $line;
4178 my $n = scalar @c;
4179 my $in_sq = 0;
4180 my $in_dq = 0;
4181 my $i = 0;
4182 while ($i < $n) {
4183 my $ch = $c[$i];
4184 if ($in_sq) { $in_sq = 0 if $ch eq "'"; $i++; next }
4185 if ($ch eq "'" && !$in_dq) { $in_sq = 1; $i++; next }
4186 if ($ch eq '"' && !$in_sq) { $in_dq = !$in_dq; $i++; next }
4187 if (!$in_sq && !$in_dq && $ch eq '\\') { $i += 2; next }
4188 if (!$in_sq && !$in_dq && $ch eq '<' && $i+2 < $n
4189 && $c[$i+1] eq '<' && $c[$i+2] eq '<'
4190 && !($i+3 < $n && $c[$i+3] eq '<')) {
4191 my $before = join('', @c[0 .. $i-1]);
4192 my $j = $i + 3;
4193 $j++ while $j < $n && ($c[$j] eq ' ' || $c[$j] eq "\t");
4194 my $wsq = 0;
4195 my $wdq = 0;
4196 my $word = '';
4197 while ($j < $n) {
4198 my $cc = $c[$j];
4199 if ($wsq) { $word .= $cc; $wsq = 0 if $cc eq "'"; $j++; next }
4200 if ($cc eq "'" && !$wdq) { $wsq = 1; $word .= $cc; $j++; next }
4201 if ($cc eq '"' && !$wsq) { $wdq = !$wdq; $word .= $cc; $j++; next }
4202 last if !$wsq && !$wdq && $cc =~ /\s/;
4203 $word .= $cc; $j++;
4204 }
4205 my $after = join('', @c[$j .. $n-1]);
4206 return ($before . $after, _arr_dequote($word));
4207 }
4208 $i++;
4209 }
4210 return ($line, undef);
4211 }
4212  
4213 # _read_redir_word: read a redirection target starting at index $start,
4214 # honouring '...' and "..." quoting and backslash escapes so that a
4215 # quoted space stays part of the single filename. Stops at the first
4216 # UNQUOTED whitespace or '<'/'>'. Returns ($raw, $next_index); $raw
4217 # still carries its quote characters -- pass it through _arr_dequote()
4218 # before use. Perl 5.005_03 compatible (index-based scan, no regex on
4219 # the whole word, no prototypes).
4220 sub _read_redir_word {
4221 my ($chars, $start, $n) = @_;
4222 my $raw = '';
4223 my $j = $start;
4224 my $sq = 0;
4225 my $dq = 0;
4226 while ($j < $n) {
4227 my $c = $chars->[$j];
4228 if ($sq) {
4229 $raw .= $c;
4230 $sq = 0 if $c eq "'";
4231 $j++; next;
4232 }
4233 if ($c eq "'" && !$dq) { $sq = 1; $raw .= $c; $j++; next }
4234 if ($c eq '"' && !$sq) { $dq = !$dq; $raw .= $c; $j++; next }
4235 if ($c eq "\\" && !$sq) {
4236 $raw .= $c; $j++;
4237 $raw .= $chars->[$j] if $j < $n;
4238 $j++; next;
4239 }
4240 last if !$dq && $c =~ /[\s<>]/;
4241 $raw .= $c; $j++;
4242 }
4243 return ($raw, $j);
4244 }
4245  
4246 sub _sh_strip_redirects {
4247 my ($line) = @_;
4248 my @chars = split //, $line;
4249 my $n = scalar @chars;
4250 my @found;
4251 my $clean = '';
4252 my $in_sq = 0;
4253 my $in_dq = 0;
4254 my $i = 0;
4255  
4256 while ($i < $n) {
4257 my $ch = $chars[$i];
4258  
4259 # Single-quote passthrough
4260 if ($in_sq) {
4261 if ($ch eq "'") { $in_sq = 0 }
4262 $clean .= $ch; $i++; next;
4263 }
4264 if ($ch eq "'" && !$in_dq) { $in_sq = 1; $clean .= $ch; $i++; next }
4265  
4266 # Double-quote toggle
4267 if ($ch eq '"' && !$in_sq) { $in_dq = !$in_dq; $clean .= $ch; $i++; next }
4268  
4269 # Inside double-quotes: only escape matters
4270 if ($in_dq) {
4271 if ($ch eq '\\') {
4272 $clean .= $ch; $i++;
4273 $clean .= $chars[$i] if $i < $n; $i++; next;
4274 }
4275 $clean .= $ch; $i++; next;
4276 }
4277  
4278 # Backslash escape outside quotes
4279 if ($ch eq '\\') {
4280 $clean .= $ch; $i++;
4281 $clean .= $chars[$i] if $i < $n; $i++; next;
4282 }
4283  
4284 # 2>&1 or 2>>&1 or 1>&2
4285 if ($ch =~ /[012]/ && $i+2 < $n
4286 && $chars[$i+1] eq '>'
4287 && ($i+3 < $n ? $chars[$i+2] eq '>' : 0)
4288 && $chars[$i+3] eq '&') {
4289 # 2>>&1 form (rare but handle)
4290 my $fd = int($ch);
4291 my $j = $i + 4;
4292 my $tgt = '';
4293 while ($j < $n && $chars[$j] =~ /\S/) { $tgt .= $chars[$j]; $j++ }
4294 push @found, [$fd, 0, "&$tgt"];
4295 $i = $j; next;
4296 }
4297 if ($ch =~ /[012]/ && $i+2 < $n
4298 && $chars[$i+1] eq '>' && $chars[$i+2] eq '&') {
4299 my $fd = int($ch);
4300 my $j = $i + 3;
4301 my $tgt = '';
4302 while ($j < $n && $chars[$j] =~ /\S/) { $tgt .= $chars[$j]; $j++ }
4303 push @found, [$fd, 0, "&$tgt"];
4304 $i = $j; next;
4305 }
4306  
4307 # fd> or fd>> (fd is 0,1,2; or implicit 1 when just > or >>)
4308 my $redir_fd = undef;
4309 if ($ch =~ /[012]/ && $i+1 < $n && $chars[$i+1] eq '>') {
4310 $redir_fd = int($ch); $i++;
4311 }
4312 elsif ($ch eq '<') {
4313 # < file (stdin)
4314 my $j = $i + 1;
4315 $j++ while $j < $n && $chars[$j] eq ' ';
4316 my ($raw, $nj) = _read_redir_word(\@chars, $j, $n);
4317 push @found, [0, 0, _arr_dequote($raw)] if $raw ne '';
4318 $i = $nj; next;
4319 }
4320 elsif ($ch eq '>') {
4321 $redir_fd = 1;
4322 }
4323  
4324 if (defined $redir_fd) {
4325 # Check for >>
4326 my $append = 0;
4327 if ($i+1 < $n && $chars[$i+1] eq '>') { $append = 1; $i++ }
4328 # Skip spaces
4329 $i++;
4330 $i++ while $i < $n && $chars[$i] eq ' ';
4331 # Read filename, honouring quotes (so a quoted space stays in
4332 # the name), then strip the quotes.
4333 my ($raw, $nj) = _read_redir_word(\@chars, $i, $n);
4334 push @found, [$redir_fd, $append, _arr_dequote($raw)] if $raw ne '';
4335 $i = $nj;
4336 next;
4337 }
4338  
4339 $clean .= $ch; $i++;
4340 }
4341  
4342 $clean =~ s/\s+\z//;
4343 return ($clean, \@found);
4344 }
4345  
4346 # ----------------------------------------------------------------
4347 # _sh_exec_with_redirs: apply I/O redirections then execute a SH line.
4348 # Perl 5.005_03 compatible: fixed bareword FHs, 2-argument open.
4349 # Supports: > >> < 2> 2>> 2>&1 1>&2
4350 # ----------------------------------------------------------------
4351 sub _sh_exec_with_redirs {
4352 my ($class, $line, $redirs_ref, $opts_ref) = @_;
4353  
4354 # Collect per-fd: stdin, stdout, stderr
4355 my ($in_file, $out_file, $out_app, $err_file, $err_app);
4356 my $err_to_stdout = 0; # 2>&1
4357 my $out_to_stderr = 0; # 1>&2
4358  
4359 for my $r (@{$redirs_ref}) {
4360 my ($fd, $append, $file) = @{$r};
4361 $file = BATsh::MB::dec($file) unless $file =~ /\A&[12]\z/;
4362 if ($fd == 0) { $in_file = $file; }
4363 elsif ($fd == 1) {
4364 if ($file eq '&2') { $out_to_stderr = 1 }
4365 else { $out_file = $file; $out_app = $append }
4366 }
4367 else { # fd == 2
4368 if ($file eq '&1') { $err_to_stdout = 1 }
4369 else { $err_file = $file; $err_app = $append }
4370 }
4371 }
4372  
4373 my $ok = 1;
4374 my ($saved_in, $saved_out, $saved_err) = (0, 0, 0);
4375  
4376 # --- stdin ---
4377 if (defined $in_file && $ok) {
4378 sysopen(_SH_REDIR_SRC, $in_file, O_RDONLY)
4379 or do { warn "sh: $in_file: $!\n"; $ok = 0 };
4380 if ($ok) {
4381 open(_SH_REDIR_SAVIN, '<&STDIN') or do { $ok = 0 };
4382 }
4383 if ($ok) {
4384 open(STDIN, '<&_SH_REDIR_SRC') or do { $ok = 0 };
4385 close(_SH_REDIR_SRC);
4386 $saved_in = 1;
4387 }
4388 }
4389  
4390 # --- stdout ---
4391 if (defined $out_file && $ok) {
4392 sysopen(_SH_REDIR_DST, $out_file,
4393 O_WRONLY | O_CREAT | ($out_app ? O_APPEND : O_TRUNC), 0666)
4394 or do { warn "sh: $out_file: $!\n"; $ok = 0 };
4395 if ($ok) {
4396 open(_SH_REDIR_SAVOUT, '>&STDOUT') or do { $ok = 0 };
4397 }
4398 if ($ok) {
4399 open(STDOUT, '>&_SH_REDIR_DST') or do { $ok = 0 };
4400 close(_SH_REDIR_DST);
4401 $saved_out = 1;
4402 }
4403 }
4404 elsif ($out_to_stderr && $ok) {
4405 open(_SH_REDIR_SAVOUT, '>&STDOUT') or do { $ok = 0 };
4406 if ($ok) {
4407 open(STDOUT, '>&STDERR') or do { $ok = 0 };
4408 $saved_out = 1;
4409 }
4410 }
4411  
4412 # --- stderr ---
4413 if (defined $err_file && $ok) {
4414 sysopen(_SH_REDIR_DST, $err_file,
4415 O_WRONLY | O_CREAT | ($err_app ? O_APPEND : O_TRUNC), 0666)
4416 or do { warn "sh: $err_file: $!\n"; $ok = 0 };
4417 if ($ok) {
4418 open(_SH_REDIR_SAVERR, '>&STDERR') or do { $ok = 0 };
4419 }
4420 if ($ok) {
4421 open(STDERR, '>&_SH_REDIR_DST') or do { $ok = 0 };
4422 close(_SH_REDIR_DST);
4423 $saved_err = 1;
4424 }
4425 }
4426 elsif ($err_to_stdout && $ok) {
4427 # Redirect stderr to the current STDOUT (which may itself be redirected)
4428 open(_SH_REDIR_SAVERR, '>&STDERR') or do { $ok = 0 };
4429 if ($ok) {
4430 open(STDERR, '>&STDOUT') or do { $ok = 0 };
4431 $saved_err = 1;
4432 }
4433 }
4434  
4435 my $rc = 0;
4436 if ($ok) {
4437 $rc = _exec_line($class, $line, $opts_ref);
4438 }
4439  
4440 # Restore in reverse order
4441 if ($saved_err) { open(STDERR, '>&_SH_REDIR_SAVERR'); close(_SH_REDIR_SAVERR) }
4442 if ($saved_out) { open(STDOUT, '>&_SH_REDIR_SAVOUT'); close(_SH_REDIR_SAVOUT) }
4443 if ($saved_in) { open(STDIN, '<&_SH_REDIR_SAVIN'); close(_SH_REDIR_SAVIN) }
4444  
4445 return $rc;
4446 }
4447  
4448 # ----------------------------------------------------------------
4449 # _split_top_semi: split a physical line on TOP-LEVEL ';' only, keeping
4450 # single/double quotes, backticks, $(...) / ${...} / <(...) / >(...)
4451 # and plain (...) groups opaque. Returns the ';'-separated segments
4452 # (the ';' itself is not included). Used by the inline-control
4453 # expander (_inline_expand) and by _inline_has_terminator. Pure Perl
4454 # 5.005_03 (hand-rolled char scan; no regex features).
4455 # ----------------------------------------------------------------
4456 sub _split_top_semi {
4457 my ($line) = @_;
4458 my @segs;
4459 my $cur = '';
4460 my $in_sq = 0;
4461 my $in_dq = 0;
4462 my $in_bt = 0; # backtick `...`
4463 my $pdep = 0; # ( ) depth (covers $( <( >( and plain ( )
4464 my $bdep = 0; # ${ } depth
4465 my @c = split //, $line;
4466 my $n = scalar @c;
4467 my $i = 0;
4468  
4469 while ($i < $n) {
4470 my $ch = $c[$i];
4471  
4472 if ($in_sq) {
4473 $cur .= $ch; $in_sq = 0 if $ch eq "'"; $i++; next;
4474 }
4475 if ($ch eq "'" && !$in_dq && !$in_bt) { $in_sq = 1; $cur .= $ch; $i++; next }
4476 if ($ch eq '"' && !$in_bt) { $in_dq = !$in_dq; $cur .= $ch; $i++; next }
4477  
4478 # Backslash escape: copy the next char verbatim
4479 if ($ch eq '\\') {
4480 $cur .= $ch; $i++;
4481 $cur .= $c[$i] if $i < $n; $i++; next;
4482 }
4483  
4484 if ($ch eq '`') { $in_bt = !$in_bt; $cur .= $ch; $i++; next }
4485  
4486 if (!$in_dq) {
4487 if ($ch eq '$' && $i+1 < $n && $c[$i+1] eq '{') {
4488 $bdep++; $cur .= '${'; $i += 2; next;
4489 }
4490 if ($bdep > 0 && $ch eq '}') { $bdep--; $cur .= $ch; $i++; next }
4491 if ($ch eq '(') { $pdep++; $cur .= $ch; $i++; next }
4492 if ($ch eq ')' && $pdep > 0) { $pdep--; $cur .= $ch; $i++; next }
4493 }
4494  
4495 if (!$in_dq && !$in_bt && $pdep == 0 && $bdep == 0 && $ch eq ';') {
4496 push @segs, $cur; $cur = ''; $i++;
4497 # collapse a following ';' (e.g. ";;") into the same split so
4498 # empty segments are not produced for the common cases
4499 next;
4500 }
4501  
4502 $cur .= $ch; $i++;
4503 }
4504 push @segs, $cur;
4505 return @segs;
4506 }
4507  
4508 # _inline_has_terminator: does the SINGLE physical line hold, as a
4509 # top-level ';'-delimited segment, a bare terminator word ($term, e.g.
4510 # 'fi' / 'done' / 'esac')? Used to detect a fully-inline control
4511 # structure written on one physical line.
4512 sub _inline_has_terminator {
4513 my ($line, $term) = @_;
4514 return 0 unless defined $line;
4515 for my $seg (_split_top_semi($line)) {
4516 my $s = $seg;
4517 $s =~ s/\A\s+//; $s =~ s/\s+\z//;
4518 return 1 if lc($s) eq lc($term);
4519 }
4520 return 0;
4521 }
4522  
4523 # _inline_expand: turn a fully-inline control-structure physical line
4524 # into the list of "logical lines" the multi-line block parsers expect.
4525 # It splits on top-level ';' and then peels a leading 'then'/'do'/'else'
4526 # keyword off its segment onto its own logical line (so "then echo a"
4527 # becomes "then" + "echo a"), which is exactly the shape _parse_if /
4528 # _parse_for / _parse_while consume line-by-line.
4529 sub _inline_expand {
4530 my ($line) = @_;
4531 my @out;
4532 for my $seg (_split_top_semi($line)) {
4533 my $s = $seg;
4534 $s =~ s/\A\s+//; $s =~ s/\s+\z//;
4535 next if $s eq '';
4536 if ($s =~ /\A(then|do|else)\b\s*(.*)\z/is) {
4537 my ($kw, $tail) = (lc($1), $2);
4538 push @out, $kw;
4539 push @out, $tail if defined $tail && $tail =~ /\S/;
4540 }
4541 else {
4542 push @out, $s;
4543 }
4544 }
4545 return @out;
4546 }
4547  
4548 # _strip_sh_comment: remove a trailing "# ..." comment from one SH
4549 # physical line. A '#' introduces a comment only when it is unquoted,
4550 # outside any $(...)/${...}/`...` region, and begins a word (preceded by
4551 # the start of line or by whitespace / ; / & / | / '(' ). This leaves
4552 # parameter forms such as $#, ${#var}, ${var#pat} and an in-word '#'
4553 # (echo a#b, http://h#frag) untouched, matching POSIX shells. Pure Perl
4554 # 5.005_03 (hand-rolled scan; no regex features).
4555 sub _strip_sh_comment {
4556 my ($line) = @_;
4557 return $line unless defined $line && index($line, '#') >= 0;
4558 my @c = split //, $line;
4559 my $n = scalar @c;
4560 my $in_sq = 0;
4561 my $in_dq = 0;
4562 my $in_bt = 0;
4563 my $pdep = 0;
4564 my $bdep = 0;
4565 my $prev = ''; # previous scanned char (for word-boundary test)
4566 my $i = 0;
4567 while ($i < $n) {
4568 my $ch = $c[$i];
4569 if ($in_sq) { $in_sq = 0 if $ch eq "'"; $prev = $ch; $i++; next }
4570 if ($ch eq "'" && !$in_dq && !$in_bt) { $in_sq = 1; $prev = $ch; $i++; next }
4571 if ($ch eq '"' && !$in_bt) { $in_dq = !$in_dq; $prev = $ch; $i++; next }
4572 if ($ch eq '\\') { $prev = 'x'; $i += 2; next }
4573 if ($ch eq '`') { $in_bt = !$in_bt; $prev = $ch; $i++; next }
4574 if (!$in_dq && !$in_bt) {
4575 if ($ch eq '$' && $i+1 < $n && $c[$i+1] eq '{') { $bdep++; $prev = '{'; $i += 2; next }
4576 if ($bdep > 0 && $ch eq '}') { $bdep--; $prev = $ch; $i++; next }
4577 if ($ch eq '(') { $pdep++; $prev = $ch; $i++; next }
4578 if ($ch eq ')' && $pdep > 0) { $pdep--; $prev = $ch; $i++; next }
4579 }
4580 if ($ch eq '#' && !$in_sq && !$in_dq && !$in_bt && $pdep == 0 && $bdep == 0) {
4581 if ($prev eq '' || $prev =~ /\s/
4582 || $prev eq ';' || $prev eq '&' || $prev eq '|' || $prev eq '(') {
4583 my $out = ($i > 0) ? join('', @c[0 .. $i-1]) : '';
4584 $out =~ s/\s+\z//;
4585 return $out;
4586 }
4587 }
4588 $prev = $ch; $i++;
4589 }
4590 return $line;
4591 }
4592  
4593 # _if_depth_delta: net change in if/fi nesting contributed by one
4594 # physical line, counting only command-position 'if' openers (+1) and
4595 # 'fi' closers (-1). A fully-inline "if ...; then ...; fi" nets to 0.
4596 # Used by _parse_if's body collector so a nested if is not closed by the
4597 # outer 'fi'. Other block types (for/while/case) use different
4598 # terminators (done/esac) and so never affect the if/fi balance.
4599 sub _if_depth_delta {
4600 my ($line) = @_;
4601 my $d = 0;
4602 for my $seg (_split_top_semi($line)) {
4603 my $s = $seg;
4604 $s =~ s/\A\s+//;
4605 $s =~ s/\A(?:then|do|else)\b\s*//i; # peel a leading block keyword
4606 my ($w) = ($s =~ /\A(\S+)/);
4607 $w = defined($w) ? lc($w) : '';
4608 $d++ if $w eq 'if';
4609 $d-- if $w eq 'fi';
4610 }
4611 return $d;
4612 }
4613  
4614 # _find_control_split: when a physical line does NOT begin with a
4615 # control-structure keyword but a control opener (if/for/while/until/
4616 # case/select) appears later in COMMAND position immediately after a
4617 # top-level ';' separator (e.g. x=""; if [ -z "$x" ]; then ...; fi),
4618 # return the byte offset at which that opener begins so the caller can
4619 # run the prefix and then re-dispatch the control structure through the
4620 # normal block parser. Only a ';' separator is honoured (sequential,
4621 # so splitting is semantically safe); a control opener after && / || is
4622 # left alone. Returns undef when there is nothing to split.
4623 sub _find_control_split {
4624 my ($line) = @_;
4625 return undef unless defined $line;
4626 my @c = split //, $line;
4627 my $n = scalar @c;
4628 my $in_sq = 0;
4629 my $in_dq = 0;
4630 my $in_bt = 0;
4631 my $pdep = 0;
4632 my $bdep = 0;
4633 my $i = 0;
4634 my $cmd_pos = 1; # are we at the start of a command word?
4635  
4636 while ($i < $n) {
4637 my $ch = $c[$i];
4638  
4639 if ($in_sq) { $in_sq = 0 if $ch eq "'"; $i++; next }
4640 if ($ch eq "'" && !$in_dq && !$in_bt) { $in_sq = 1; $cmd_pos = 0; $i++; next }
4641 if ($ch eq '"' && !$in_bt) { $in_dq = !$in_dq; $cmd_pos = 0; $i++; next }
4642 if ($ch eq '\\') { $i += 2; $cmd_pos = 0; next }
4643 if ($ch eq '`') { $in_bt = !$in_bt; $cmd_pos = 0; $i++; next }
4644  
4645 if (!$in_dq && !$in_bt) {
4646 if ($ch eq '$' && $i+1 < $n && $c[$i+1] eq '{') { $bdep++; $i += 2; $cmd_pos = 0; next }
4647 if ($bdep > 0 && $ch eq '}') { $bdep--; $i++; next }
4648 if ($ch eq '(') { $pdep++; $i++; $cmd_pos = 1; next }
4649 if ($ch eq ')' && $pdep > 0) { $pdep--; $i++; next }
4650 }
4651  
4652 if (!$in_dq && !$in_bt && $pdep == 0 && $bdep == 0) {
4653 if ($ch eq ';') { $cmd_pos = 1; $i++; next }
4654 if ($ch eq '&' && $i+1 < $n && $c[$i+1] eq '&') { $cmd_pos = 0; $i += 2; next }
4655 if ($ch eq '|' && $i+1 < $n && $c[$i+1] eq '|') { $cmd_pos = 0; $i += 2; next }
4656 if ($ch eq '|' || $ch eq '&') { $cmd_pos = 0; $i++; next }
4657 if ($ch =~ /\s/) { $i++; next } # whitespace keeps command position
4658  
4659 # A non-space, non-separator byte: if we are at command
4660 # position and NOT at the very start (offset 0), test for a
4661 # control opener keyword here.
4662 if ($cmd_pos && $i > 0) {
4663 my $tail = join('', @c[$i .. $n-1]);
4664 if ($tail =~ /\A(if|for|while|until|case|select)\b/i) {
4665 return $i;
4666 }
4667 }
4668 $cmd_pos = 0; $i++; next;
4669 }
4670  
4671 $i++;
4672 }
4673 return undef;
4674 }
4675  
4676 # ----------------------------------------------------------------
4677 sub _split_sh_compound {
4678 my ($line) = @_;
4679 my @parts;
4680 my $cur = '';
4681 my $in_sq = 0;
4682 my $in_dq = 0;
4683 my $depth = 0; # $( / <( / >( nesting
4684 my $ctl = 0; # control-structure nesting: if/for/while/until/case/
4685 # select ... fi/done/esac. While >0, a ';' / && / ||
4686 # belongs to the compound command and is NOT a
4687 # top-level separator (so cmd | while x; do y; done
4688 # and a && for i in ..; do ..; done stay intact).
4689 my $cmdpos = 1; # true when the next word is in command position
4690 my @chars = split //, $line;
4691 my $n = scalar @chars;
4692 my $i = 0;
4693  
4694 while ($i < $n) {
4695 my $ch = $chars[$i];
4696  
4697 # Single-quote region
4698 if ($in_sq) {
4699 if ($ch eq "'") { $in_sq = 0 }
4700 $cur .= $ch; $i++; next;
4701 }
4702 if ($ch eq "'" && !$in_dq) { $in_sq = 1; $cur .= $ch; $i++; $cmdpos = 0; next }
4703  
4704 # Double-quote toggle
4705 if ($ch eq '"' && !$in_sq) { $in_dq = !$in_dq; $cur .= $ch; $i++; $cmdpos = 0; next }
4706  
4707 # $( nesting inside double-quotes
4708 if ($in_dq) {
4709 if ($ch eq '$' && $i+1 < $n && $chars[$i+1] eq '(') { $depth++ }
4710 elsif ($ch eq ')' && $depth > 0) { $depth-- }
4711 $cur .= $ch; $i++; next;
4712 }
4713  
4714 # Track $( nesting outside quotes
4715 if ($ch eq '$' && $i+1 < $n && $chars[$i+1] eq '(') {
4716 $depth++; $cur .= $ch; $i++; $cmdpos = 0; next;
4717 }
4718  
4719 # Track <( / >( process-substitution nesting outside quotes
4720 if (($ch eq '<' || $ch eq '>') && $i+1 < $n && $chars[$i+1] eq '(') {
4721 $depth++; $cur .= $ch; $i++; $cmdpos = 0; next;
4722 }
4723 if ($ch eq ')' && $depth > 0) {
4724 $depth--; $cur .= $ch; $i++; $cmdpos = 0; next;
4725 }
4726  
4727 # Inside $(...) don't split on operators or track control words
4728 if ($depth > 0) { $cur .= $ch; $i++; next }
4729  
4730 # Backslash escape
4731 if ($ch eq '\\') {
4732 $cur .= $ch; $i++;
4733 $cur .= $chars[$i] if $i < $n; $i++; $cmdpos = 0; next;
4734 }
4735  
4736 # && operator
4737 if ($ch eq '&' && $i+1 < $n && $chars[$i+1] eq '&') {
4738 if ($ctl == 0) {
4739 push @parts, { op => '', cmd => $cur };
4740 push @parts, { op => '&&', cmd => '' };
4741 $cur = '';
4742 }
4743 else { $cur .= '&&' }
4744 $i += 2; $cmdpos = 1; next;
4745 }
4746  
4747 # || operator
4748 if ($ch eq '|' && $i+1 < $n && $chars[$i+1] eq '|') {
4749 if ($ctl == 0) {
4750 push @parts, { op => '', cmd => $cur };
4751 push @parts, { op => '||', cmd => '' };
4752 $cur = '';
4753 }
4754 else { $cur .= '||' }
4755 $i += 2; $cmdpos = 1; next;
4756 }
4757  
4758 # ; separator (not inside any quote or subst)
4759 if ($ch eq ';') {
4760 if ($ctl == 0) {
4761 push @parts, { op => '', cmd => $cur };
4762 push @parts, { op => ';', cmd => '' };
4763 $cur = '';
4764 }
4765 else { $cur .= ';' }
4766 $i++; $cmdpos = 1; next;
4767 }
4768  
4769 # Single | (pipe): not a compound separator here, but the word that
4770 # follows it is in command position (so x | while ... is tracked).
4771 if ($ch eq '|') { $cur .= $ch; $i++; $cmdpos = 1; next }
4772  
4773 # '(' opens a group; the next word is in command position.
4774 if ($ch eq '(') { $cur .= $ch; $i++; $cmdpos = 1; next }
4775  
4776 # Whitespace: preserved; does not itself change command position.
4777 if ($ch =~ /\s/) { $cur .= $ch; $i++; next }
4778  
4779 # A word starting in command position may be a control keyword.
4780 if ($cmdpos && $ch =~ /[A-Za-z]/) {
4781 my $j = $i;
4782 my $w = '';
4783 while ($j < $n && $chars[$j] =~ /[A-Za-z]/) { $w .= $chars[$j]; $j++ }
4784 my $after = ($j < $n) ? $chars[$j] : '';
4785 # A full word only if the next char terminates it.
4786 if ($after eq '' || $after =~ /[\s;&|)]/) {
4787 my $lw = lc $w;
4788 if ( $lw eq 'if' || $lw eq 'for' || $lw eq 'while'
4789 || $lw eq 'until'|| $lw eq 'case' || $lw eq 'select') {
4790 $ctl++;
4791 }
4792 elsif ($lw eq 'fi' || $lw eq 'done' || $lw eq 'esac') {
4793 $ctl-- if $ctl > 0;
4794 }
4795 $cur .= $w;
4796 $i = $j;
4797 # do/then/else/elif introduce a fresh command position.
4798 $cmdpos = ($lw eq 'do' || $lw eq 'then'
4799 || $lw eq 'else' || $lw eq 'elif') ? 1 : 0;
4800 next;
4801 }
4802 }
4803  
4804 # Ordinary character (part of a word / argument).
4805 $cur .= $ch; $i++; $cmdpos = 0;
4806 }
4807 push @parts, { op => '', cmd => $cur };
4808  
4809 # If only one cmd part with no operators, return single element
4810 my $has_op = 0;
4811 for my $p (@parts) { $has_op = 1 if $p->{op} ne '' }
4812 return @parts if $has_op;
4813 return ({ op => '', cmd => $line });
4814 }
4815  
4816 # ----------------------------------------------------------------
4817 # _exec_sh_compound: execute && / || / ; compound SH commands
4818 # ----------------------------------------------------------------
4819 sub _exec_sh_compound {
4820 my ($class, $parts, $opts_ref) = @_;
4821 my $pending_op = '';
4822 my $rc = 0;
4823  
4824 # set -e semantics for lists: a command is EXEMPT when a && or ||
4825 # operator appears anywhere AFTER it in the list (bash: every command
4826 # of a && / || list except the one following the final && or ||).
4827 # Commands separated only by ; are ordinary statements and DO trigger.
4828 # Adjudication happens here, per member, so _run_lines must not check
4829 # the list's overall status again: signal that via $_ERREXIT_DONE.
4830 my $ncmd = 0;
4831 for my $part (@{$parts}) { $ncmd++ if $part->{op} eq '' }
4832 $_ERREXIT_DONE = 1 if $ncmd > 1;
4833  
4834 my $seen_cmds = 0;
4835 for my $k (0 .. $#{$parts}) {
4836 my $part = $parts->[$k];
4837 my $op = $part->{op};
4838 my $cmd = $part->{cmd};
4839 $cmd =~ s/\A\s+//; $cmd =~ s/\s+\z//;
4840  
4841 # A prior member executed exit / errexit / break / return: stop.
4842 last if defined $_EXIT_CODE || $_BREAK || $_RETURN;
4843  
4844 if ($op eq '') {
4845 $seen_cmds++;
4846 # Exempt from set -e when a && or || follows later in the list
4847 my $exempt = 0;
4848 for my $j ($k + 1 .. $#{$parts}) {
4849 my $later = $parts->[$j]{op};
4850 if ($later eq '&&' || $later eq '||') { $exempt = 1; last }
4851 }
4852 my $ran = 0;
4853 # Execute according to pending operator
4854 if ($pending_op eq '') {
4855 if ($cmd =~ /\S/) { $ran = 1 }
4856 }
4857 elsif ($pending_op eq '&&') {
4858 if ($LAST_STATUS == 0 && $cmd =~ /\S/) { $ran = 1 }
4859 }
4860 elsif ($pending_op eq '||') {
4861 if ($LAST_STATUS != 0 && $cmd =~ /\S/) { $ran = 1 }
4862 }
4863 elsif ($pending_op eq ';') {
4864 if ($cmd =~ /\S/) { $ran = 1 }
4865 }
4866 if ($ran) {
4867 if ($exempt) {
4868 $_ERREXIT_HOLD++;
4869 $rc = _exec_line($class, $cmd, $opts_ref);
4870 $_ERREXIT_HOLD--;
4871 }
4872 else {
4873 $rc = _exec_line($class, $cmd, $opts_ref);
4874 _errexit_check($rc);
4875 }
4876 }
4877 $pending_op = '';
4878 }
4879 else {
4880 $pending_op = $op;
4881 }
4882 }
4883 return $rc;
4884 }
4885  
4886 # ----------------------------------------------------------------
4887 sub _split_sh_pipe {
4888 my ($line) = @_;
4889 my @segs;
4890 my $cur = '';
4891 my $in_sq = 0; # inside single quotes
4892 my $in_dq = 0; # inside double quotes
4893 my $depth = 0; # $( nesting depth
4894 my @chars = split //, $line;
4895 my $n = scalar @chars;
4896 my $i = 0;
4897  
4898 while ($i < $n) {
4899 my $ch = $chars[$i];
4900  
4901 # Single-quote region: nothing special until closing '
4902 if ($in_sq) {
4903 if ($ch eq "'") { $in_sq = 0 }
4904 $cur .= $ch; $i++; next;
4905 }
4906  
4907 # Toggle double-quote
4908 if ($ch eq '"' && !$in_sq) {
4909 $in_dq = !$in_dq;
4910 $cur .= $ch; $i++; next;
4911 }
4912  
4913 # Inside double-quotes only $( nesting matters
4914 if ($in_dq) {
4915 if ($ch eq '$' && $i+1 < $n && $chars[$i+1] eq '(') {
4916 $depth++; $cur .= $ch; $i++; next;
4917 }
4918 if ($ch eq ')' && $depth > 0) {
4919 $depth--; $cur .= $ch; $i++; next;
4920 }
4921 # backslash escape inside "
4922 if ($ch eq '\\') {
4923 $cur .= $ch; $i++;
4924 $cur .= $chars[$i] if $i < $n; $i++; next;
4925 }
4926 $cur .= $ch; $i++; next;
4927 }
4928  
4929 # Enter single-quote
4930 if ($ch eq "'") { $in_sq = 1; $cur .= $ch; $i++; next }
4931  
4932 # $( command substitution: consume BOTH characters and bump the
4933 # nesting depth exactly ONCE here, so the standalone-'(' handler
4934 # below does not double-count the '(' of a $( and leave depth
4935 # stuck at 1 after the matching ')'. (That stale depth made a
4936 # bare '|' following a nested $(...) fail to split as a pipe.)
4937 if ($ch eq '$' && $i+1 < $n && $chars[$i+1] eq '(') {
4938 $depth++; $cur .= '$('; $i += 2; next;
4939 }
4940  
4941 # <( / >( process substitution (v0.07): same "consume both
4942 # characters, bump depth exactly once" treatment as $( above, so
4943 # a '|' inside its body is not mistaken for the outer pipeline's
4944 # separator.
4945 if (($ch eq '<' || $ch eq '>') && $i+1 < $n && $chars[$i+1] eq '(') {
4946 $depth++; $cur .= $ch . '('; $i += 2; next;
4947 }
4948 if ($ch eq '(' ) { $depth++ if $depth > 0; $cur .= $ch; $i++; next }
4949 if ($ch eq ')' ) {
4950 if ($depth > 0) { $depth-- }
4951 $cur .= $ch; $i++; next;
4952 }
4953  
4954 # Bare | outside any quote/subst => pipeline separator
4955 if ($ch eq '|' && $depth == 0) {
4956 # Peek: || is logical-or, not a pipe
4957 if ($i+1 < $n && $chars[$i+1] eq '|') {
4958 $cur .= '||'; $i += 2; next;
4959 }
4960 push @segs, $cur;
4961 $cur = '';
4962 $i++; next;
4963 }
4964  
4965 # Backslash escape (outside quotes)
4966 if ($ch eq '\\') {
4967 $cur .= $ch; $i++;
4968 $cur .= $chars[$i] if $i < $n; $i++; next;
4969 }
4970  
4971 $cur .= $ch; $i++;
4972 }
4973 push @segs, $cur;
4974 return @segs;
4975 }
4976  
4977 # ----------------------------------------------------------------
4978 # _seg_is_control: true when a pipeline segment is a compound/control
4979 # construct that must be run through _run_lines (the block dispatcher)
4980 # rather than _exec_line (which would try to exec "while"/"for"/... as an
4981 # external command). Recognises the command-position control keywords and
4982 # a "( subshell )" group. Enables the common cmd | while read ... ; done
4983 # and cmd | for x in ...; done idioms. Pure Perl 5.005_03.
4984 sub _seg_is_control {
4985 my ($seg) = @_;
4986 my $s = defined($seg) ? $seg : '';
4987 $s =~ s/\A\s+//;
4988 my ($w) = ($s =~ /\A(\S+)/);
4989 return 0 unless defined $w;
4990 $w = lc $w;
4991 return 1 if $w eq 'while' || $w eq 'until' || $w eq 'for'
4992 || $w eq 'if' || $w eq 'case' || $w eq 'select';
4993 return 1 if $s =~ /\A\(/ && $s !~ /\A\(\(/; # ( subshell ) group
4994 return 0;
4995 }
4996  
4997 # _exec_sh_pipe: run a SH pipeline via temporary files.
4998 # Each segment's stdout feeds the next segment's stdin.
4999 # Perl 5.005_03 compatible: bareword FHs, 2-arg open.
5000 # ----------------------------------------------------------------
5001 sub _exec_sh_pipe {
5002 my ($class, $segs_ref, $opts_ref) = @_;
5003 my @segs = @{$segs_ref};
5004 my $n_segs = scalar @segs;
5005 # Tag the stage files with the active pipeline-nesting depth so a nested
5006 # pipeline (reached when a segment contains a $(...) that is itself a
5007 # pipeline) gets distinct stage files and does not clobber this one.
5008 local $_PIPE_DEPTH = $_PIPE_DEPTH + 1;
5009 my $base = File::Spec->catfile(File::Spec->tmpdir(),
5010 'batsh_shp_' . $$ . '_' . $_PIPE_DEPTH);
5011 # Localize the dup/stage filehandle globs so that a nested pipeline
5012 # (a segment whose $(...) body is itself a pipeline) does not overwrite
5013 # this pipeline's saved STDOUT/STDIN handles. Perl 5.005_03 compatible.
5014 local (*_SH_PIPE_RFH, *_SH_PIPE_WFH, *_SH_PIPE_SAVIN, *_SH_PIPE_SAVOUT);
5015 my $rc = 0;
5016 my $input_f = undef; # tmpfile that feeds this segment's STDIN
5017  
5018 for my $idx (0 .. $n_segs - 1) {
5019 my $seg = $segs[$idx];
5020 $seg =~ s/\A\s+//; $seg =~ s/\s+\z//;
5021 next unless $seg =~ /\S/;
5022  
5023 my $is_last = ($idx == $n_segs - 1) ? 1 : 0;
5024 my $output_f = undef;
5025  
5026 # --- redirect STDIN from previous segment's output ---
5027 my $saved_in = 0;
5028 if (defined $input_f && -f $input_f) {
5029 open(_SH_PIPE_RFH, $input_f)
5030 or do { warn "SH pipe: open $input_f: $!\n"; last };
5031 open(_SH_PIPE_SAVIN, '<&STDIN')
5032 or do { close(_SH_PIPE_RFH); last };
5033 open(STDIN, '<&_SH_PIPE_RFH')
5034 or do {
5035 close(_SH_PIPE_RFH);
5036 open(STDIN, '<&_SH_PIPE_SAVIN'); close(_SH_PIPE_SAVIN);
5037 last;
5038 };
5039 close(_SH_PIPE_RFH);
5040 $saved_in = 1;
5041 }
5042  
5043 # --- redirect STDOUT to next segment's input file ---
5044 my $saved_out = 0;
5045 unless ($is_last) {
5046 $output_f = _shp_tempfile("${base}_${idx}");
5047 if (!defined $output_f) {
5048 if ($saved_in) {
5049 open(STDIN, '<&_SH_PIPE_SAVIN'); close(_SH_PIPE_SAVIN);
5050 }
5051 warn "SH pipe: cannot create stage temp file\n";
5052 last;
5053 }
5054 open(_SH_PIPE_SAVOUT, '>&STDOUT')
5055 or do {
5056 close(_SH_PIPE_WFH);
5057 if ($saved_in) {
5058 open(STDIN, '<&_SH_PIPE_SAVIN'); close(_SH_PIPE_SAVIN);
5059 }
5060 last;
5061 };
5062 open(STDOUT, '>&_SH_PIPE_WFH')
5063 or do {
5064 close(_SH_PIPE_WFH);
5065 open(STDOUT, '>&_SH_PIPE_SAVOUT'); close(_SH_PIPE_SAVOUT);
5066 if ($saved_in) {
5067 open(STDIN, '<&_SH_PIPE_SAVIN'); close(_SH_PIPE_SAVIN);
5068 }
5069 last;
5070 };
5071 close(_SH_PIPE_WFH);
5072 $saved_out = 1;
5073 }
5074  
5075 # --- execute the segment as a SH line ---
5076 # (_exec_line_impl routes a control/compound segment such as
5077 # "while read ...; do ...; done" through the block runner, so the
5078 # common cmd | while read ... idiom works.)
5079 $rc = _exec_line($class, $seg, $opts_ref);
5080  
5081 # --- restore STDOUT ---
5082 if ($saved_out) {
5083 open(STDOUT, '>&_SH_PIPE_SAVOUT');
5084 close(_SH_PIPE_SAVOUT);
5085 }
5086  
5087 # --- restore STDIN and remove input tmpfile ---
5088 if ($saved_in) {
5089 open(STDIN, '<&_SH_PIPE_SAVIN');
5090 close(_SH_PIPE_SAVIN);
5091 unlink $input_f;
5092 @_SHP_TMPFILES = grep { $_ ne $input_f } @_SHP_TMPFILES;
5093 }
5094  
5095 $input_f = $output_f;
5096 }
5097  
5098 if (defined $input_f && -f $input_f) {
5099 unlink $input_f;
5100 @_SHP_TMPFILES = grep { $_ ne $input_f } @_SHP_TMPFILES;
5101 }
5102 return $rc;
5103 }
5104  
5105 # _shp_tempfile: create a unique, empty temp file for one pipeline stage's
5106 # stdout->stdin bridge, using sysopen(...O_CREAT|O_EXCL...) to avoid symlink
5107 # races (mirrors _bg_tempfile / _hd_tempfile / _subst_tempfile). Opens the
5108 # package bareword filehandle _SH_PIPE_WFH and returns the final path, or
5109 # undef on failure. $stub is the depth/index-tagged path prefix so stage
5110 # files stay distinguishable for debugging; a sequence number is appended
5111 # to make the final name unique and unpredictable.
5112 sub _shp_tempfile {
5113 my ($stub) = @_;
5114 my $attempt = 0;
5115 while ($attempt < 1000) {
5116 $_PIPE_SEQ++;
5117 $attempt++;
5118 my $path = $stub . '_' . $_PIPE_SEQ . '.tmp';
5119 if (sysopen(_SH_PIPE_WFH, $path, O_WRONLY | O_CREAT | O_EXCL, 0600)) {
5120 push @_SHP_TMPFILES, $path;
5121 return $path;
5122 }
5123 # EEXIST or transient error: retry with next sequence number
5124 }
5125 return undef;
5126 }
5127  
5128 # ----------------------------------------------------------------
5129 # Pattern helpers for ${var%pat}, ${var#pat}, ${var/pat/rep}
5130 # Converts glob-style pattern to Perl regex (*, ?, [abc]).
5131 # ----------------------------------------------------------------
5132 # ----------------------------------------------------------------
5133 # _glob_expand: expand a single word that contains unquoted glob
5134 # metacharacters (* ? [...]) into a sorted list of matching pathnames.
5135 # Returns the original word unchanged if no matches are found (POSIX
5136 # "nullglob off" behaviour, which is the shell default).
5137 # Only words that were NOT wrapped in quotes are eligible; the caller
5138 # is responsible for passing only unquoted words.
5139 # ----------------------------------------------------------------
5140 sub _glob_expand {
5141 my ($word) = @_;
5142 # Fast path: no metacharacters
5143 return ($word) unless $word =~ /[*?\[]/;
5144 # The matcher has to see the real pathname, so a backslash still held
5145 # behind its expansion-result sentinel (a Windows path that came out
5146 # of a variable) is restored first. What comes back is data again and
5147 # is re-protected, so the quote-removal stage downstream cannot eat
5148 # the separators of the very names it just matched.
5149 my $pat = _unprotect_lit($word);
5150 my @matches = map { _protect_lit(BATsh::MB::enc($_)) }
5151 _glob_paths(BATsh::MB::dec($pat));
5152 return @matches ? @matches : ($word);
5153 }
5154  
5155 # ----------------------------------------------------------------
5156 # _glob_paths: pathname expansion in pure Perl (v0.09)
5157 # ----------------------------------------------------------------
5158 # Perl's built-in glob() cannot serve a shell that has to run on Windows:
5159 # it reads a backslash as an ESCAPE character, so the perfectly ordinary
5160 # pattern C:\dir\*.txt is understood as C:dir*.txt and matches
5161 # nothing, and when a pattern matches nothing glob() hands it back with
5162 # those backslashes already deleted. File::Glob's GLOB_NOESCAPE would
5163 # avoid that, but File::Glob arrived in Perl 5.6 and BATsh supports
5164 # 5.005_03. glob() also offers no extglob support and no say over
5165 # dot-files. The pattern is therefore matched here, one path segment at
5166 # a time, with this module's own _glob_to_re() translator:
5167 #
5168 # * the pathname separator is "/" everywhere, and "\" as well on
5169 # Windows, where that is simply how a path is written. On Unix a
5170 # backslash is an ordinary character in a filename and stays one, so
5171 # a directory really named "a\b" keeps working;
5172 # * a segment holding no metacharacter is appended literally;
5173 # * a leading "." is matched only by a pattern that starts with "." --
5174 # the shell rule, which glob() follows too;
5175 # * every segment but the last has to name a directory;
5176 # * the separators the caller wrote come back unchanged, so a Windows
5177 # pattern yields Windows pathnames;
5178 # * a negated class "[!abc]" negates, and only names that exist are
5179 # returned, sorted, with case ignored on Windows.
5180 #
5181 # Returns the (possibly empty) list of matching pathnames. The caller
5182 # decides what an empty list means; POSIX leaves the word untouched.
5183 # Perl 5.005_03 safe: bareword directory handle, no File::Glob, no
5184 # File::Spec, and one directory level is read and closed at a time so the
5185 # single global handle is never nested.
5186 # ----------------------------------------------------------------
5187 sub _glob_paths {
5188 my ($pat) = @_;
5189 return () unless defined $pat && $pat ne '';
5190 my $win = ($^O =~ /MSWin32|dos|os2|cygwin/i) ? 1 : 0;
5191 my $sepclass = $win ? '[\\\\/]' : '[/]';
5192 my $nonsep = $win ? '[^\\\\/]' : '[^/]';
5193  
5194 # The leading root -- a Windows drive letter and/or separators -- is
5195 # never a pattern and is copied through as written.
5196 my $rest = $pat;
5197 my $prefix = '';
5198 if ($win && $rest =~ s/\A([A-Za-z]:)//) { $prefix = $1 }
5199 if ($rest =~ s/\A($sepclass+)//) { $prefix .= $1 }
5200  
5201 # Split the remainder into [segment, following separators] pairs.
5202 my @parts = ();
5203 while ($rest ne '') {
5204 if ($rest =~ s/\A($nonsep+)($sepclass+)//) { push @parts, [$1, $2] }
5205 elsif ($rest =~ s/\A($nonsep+)\z//) { push @parts, [$1, ''] }
5206 elsif ($rest =~ s/\A($sepclass+)//) { next }
5207 else { last }
5208 }
5209 return () unless @parts;
5210  
5211 my @cur = ($prefix);
5212 my $done = 0;
5213 my $total = scalar(@parts);
5214 for my $p (@parts) {
5215 my ($seg, $sep) = @{$p};
5216 $done++;
5217 my $last = ($done == $total) ? 1 : 0;
5218  
5219 # Is this segment a pattern at all? An unbalanced "[" is not:
5220 # treating it as a character class would let a stray bracket in
5221 # "echo [$dir]" match a one-character filename.
5222 my $is_pat = 0;
5223 $is_pat = 1 if $seg =~ /[*?]/;
5224 $is_pat = 1 if $seg =~ /\[[^\]]+\]/;
5225 $is_pat = 1 if $_OPT_EXTGLOB && $seg =~ /[?*+\@!]\(/;
5226  
5227 if (!$is_pat) {
5228 my @next = ();
5229 for my $c (@cur) { push @next, $c . $seg . $sep }
5230 @cur = @next;
5231 next;
5232 }
5233  
5234 my $re = _glob_to_re($seg, 1);
5235 $re = $win ? "(?i)\\A(?:$re)\\z" : "\\A(?:$re)\\z";
5236 # A pattern that cannot be compiled (an empty or reversed
5237 # character class, say) is taken literally, as the shell does.
5238 # The warning handler keeps such a pattern from printing a Perl
5239 # diagnostic on the script's STDERR.
5240 my $re_bad = 0;
5241 {
5242 local $SIG{'__WARN__'} = sub { 1 };
5243 eval { my $probe = 'x'; $probe =~ /$re/ };
5244 $re_bad = 1 if $@;
5245 }
5246 if ($re_bad) {
5247 my @lit = ();
5248 for my $c (@cur) { push @lit, $c . $seg . $sep }
5249 @cur = @lit;
5250 next;
5251 }
5252 my $want_dot = (index($seg, '.') == 0) ? 1 : 0;
5253 my @next = ();
5254 for my $c (@cur) {
5255 # opendir() gets the directory without its trailing separator:
5256 # Win32 turns "dir\\" into a "dir\\\\*" search pattern.
5257 my $dir = $c;
5258 if ($dir eq '') { $dir = '.' }
5259 else {
5260 my $trim = $dir;
5261 $trim =~ s/$sepclass+\z//;
5262 $dir = $trim unless $trim eq ''
5263 || ($win && $trim =~ /\A[A-Za-z]:\z/);
5264 }
5265 my @names = ();
5266 if (opendir(_GLOB_DH, $dir)) {
5267 @names = readdir(_GLOB_DH);
5268 closedir(_GLOB_DH);
5269 }
5270 local $SIG{'__WARN__'} = sub { 1 };
5271 for my $nm (sort @names) {
5272 next if !$want_dot && index($nm, '.') == 0;
5273 my $hit = 0;
5274 eval { $hit = ($nm =~ /$re/) ? 1 : 0 };
5275 next unless $hit;
5276 my $full = $c . $nm;
5277 next if !$last && !-d $full;
5278 push @next, $full . $sep;
5279 }
5280 }
5281 @cur = @next;
5282 return () unless @cur;
5283 }
5284  
5285 # Only existing names are matches. A trailing separator is dropped
5286 # for the probe, since Win32 dislikes "C:\dir\" in a file test.
5287 my @out = ();
5288 for my $c (@cur) {
5289 my $probe = $c;
5290 $probe =~ s/$sepclass+\z//;
5291 $probe = $c if $probe eq '';
5292 $probe = $c if $win && $probe =~ /\A[A-Za-z]:\z/;
5293 next unless -e $probe || -l $probe;
5294 push @out, $c;
5295 }
5296 return sort @out;
5297 }
5298  
5299  
5300 # ----------------------------------------------------------------
5301 # _raw_has_glob: true when the RAW (pre-expansion) argument text contains
5302 # a genuine, eligible filename-glob metacharacter (*, ?, [) -- one that
5303 # was actually written in the script and would trigger pathname
5304 # expansion. Used by the "echo" builtin to decide whether to run its
5305 # arguments through glob expansion, WITHOUT being fooled by:
5306 # * a metacharacter inside single or double quotes (echo "*.txt" is
5307 # literal in bash),
5308 # * the '*' of the $* / "$*" special parameter or the '?' of $? (these
5309 # are parameter references, not globs), or
5310 # * a metacharacter inside a ${...} parameter expansion (${arr[*]},
5311 # ${VAR?}), which is likewise not a glob.
5312 # The previous test -- a plain /[*?\[]/ match on the raw text -- fired on
5313 # all of these, so "echo \" x: $*\"" was needlessly re-parsed and its
5314 # leading whitespace and internal spacing collapsed.
5315 # Perl 5.005_03 compatible: single character scan, no regex features.
5316 # ----------------------------------------------------------------
5317 sub _raw_has_glob {
5318 my ($raw) = @_;
5319 return 0 unless defined $raw && $raw =~ /\S/;
5320 my @c = split //, $raw;
5321 my $n = scalar @c;
5322 my $in_sq = 0; my $in_dq = 0;
5323 my $bdep = 0; # depth inside ${ ... }
5324 my $i = 0;
5325 while ($i < $n) {
5326 my $ch = $c[$i];
5327 if ($in_sq) { $in_sq = 0 if $ch eq "'"; $i++; next }
5328 if ($ch eq "'" && !$in_dq) { $in_sq = 1; $i++; next }
5329 if ($ch eq '"') { $in_dq = !$in_dq; $i++; next }
5330 if ($ch eq '\\') { $i += 2; next } # backslash escape
5331 # Parameter expansion: $* $? $@ ... and ${ ... }
5332 if ($ch eq '$' && $i + 1 < $n) {
5333 if ($c[$i+1] eq '{') { $bdep++; $i += 2; next }
5334 # $ followed by a single special char (including * and ?) is a
5335 # parameter reference, not a glob -- skip both characters.
5336 $i += 2; next;
5337 }
5338 if ($bdep > 0) {
5339 $bdep-- if $ch eq '}';
5340 $i++; next;
5341 }
5342 # An unquoted, non-parameter glob metacharacter counts.
5343 if (!$in_sq && !$in_dq && ($ch eq '*' || $ch eq '?' || $ch eq '[')) {
5344 return 1;
5345 }
5346 $i++;
5347 }
5348 return 0;
5349 }
5350  
5351 # ----------------------------------------------------------------
5352 # _glob_expand_args: apply filename globbing to each unquoted word in
5353 # an already-split argument list. Words that were originally quoted
5354 # (single or double) must already have their quotes stripped by the
5355 # caller; we cannot distinguish them at this stage, so we re-check
5356 # for glob metacharacters and call _glob_expand only when present.
5357 # ----------------------------------------------------------------
5358 sub _glob_expand_args {
5359 my (@words) = @_;
5360 my @result;
5361 for my $w (@words) {
5362 push @result, _glob_expand($w);
5363 }
5364 return @result;
5365 }
5366  
5367 sub _glob_to_re {
5368 my ($pat, $greedy) = @_;
5369 my $re = '';
5370 my @chars = split //, $pat;
5371 my $n = scalar @chars;
5372 my $i = 0;
5373 while ($i < $n) {
5374 my $c = $chars[$i];
5375 if ($_OPT_EXTGLOB && $c =~ /[?*+\@!]/ && $i+1 < $n && $chars[$i+1] eq '(') {
5376 my @eg = _extglob_scan(\@chars, $i, sub { _glob_to_re($_[0], $greedy) });
5377 if (@eg) { $re .= $eg[1]; $i = $eg[0]; next }
5378 }
5379 if ($c eq '*') {
5380 $re .= $greedy ? '.*' : '.*?';
5381 }
5382 elsif ($c eq '?') { $re .= '.' }
5383 elsif ($c eq '[') {
5384 # POSIX character class. A leading ! (or ^) negates it -- the
5385 # shell spells the negation "[!abc]", which Perl would read as
5386 # the class of "!", "a", "b" and "c" -- and a leading ] and an
5387 # embedded backslash are literal members of the class.
5388 my $cls = '[';
5389 $i++;
5390 if ($i < $n && ($chars[$i] eq '!' || $chars[$i] eq '^')) {
5391 $cls .= '^';
5392 $i++;
5393 }
5394 if ($i < $n && $chars[$i] eq ']') { $cls .= '\\]'; $i++ }
5395 while ($i < $n && $chars[$i] ne ']') {
5396 $cls .= ($chars[$i] eq '\\') ? '\\\\' : $chars[$i];
5397 $i++;
5398 }
5399 $cls .= ']';
5400 $re .= $cls;
5401 }
5402 else { $re .= quotemeta($c) }
5403 $i++;
5404 }
5405 return $re;
5406 }
5407  
5408 sub _sh_remove_suffix {
5409 my ($val, $pat, $greedy) = @_;
5410 # % (greedy=0, shortest suffix): keep longest prefix
5411 # => /\A(.*) PATTERN \z/s with greedy prefix => $1
5412 # %% (greedy=1, longest suffix): keep shortest prefix
5413 # => /\A(.*?)PATTERN \z/s with lazy prefix => $1
5414 my $re = _glob_to_re($pat, 1); # pattern itself is always greedy for suffix
5415 if ($greedy) {
5416 # longest suffix removed: lazy prefix
5417 return ($val =~ /\A(.*?)$re\z/s) ? $1 : $val;
5418 }
5419 else {
5420 # shortest suffix removed: greedy prefix
5421 return ($val =~ /\A(.*)$re\z/s) ? $1 : $val;
5422 }
5423 }
5424  
5425 sub _sh_remove_prefix {
5426 my ($val, $pat, $greedy) = @_;
5427 # # (greedy=0, shortest prefix): keep longest suffix
5428 # => /\A PATTERN(.*) \z/s with lazy pattern => $1
5429 # ## (greedy=1, longest prefix): keep shortest suffix
5430 # => /\A PATTERN(.*) \z/s with greedy pattern => $1
5431 my $re = _glob_to_re($pat, $greedy);
5432 return ($val =~ /\A$re(.*)\z/s) ? $1 : $val;
5433 }
5434  
5435 sub _sh_replace {
5436 my ($val, $pat, $rep, $global) = @_;
5437 my $re = _glob_to_re($pat, 1);
5438 if ($global) { $val =~ s/$re/$rep/g }
5439 else { $val =~ s/$re/$rep/ }
5440 return $val;
5441 }
5442  
5443 # ----------------------------------------------------------------
5444 # Shell function registry { name => \@body_lines }
5445 # ----------------------------------------------------------------
5446  
5447 # ----------------------------------------------------------------
5448 # _inline_body_has_control: true when a single-line function body
5449 # (the text between the braces of "name() { ... }") contains a shell
5450 # control-structure keyword in command position -- if/for/while/until/
5451 # case/select as the first word, or after a ';', '&&', '||' or '|'.
5452 # Such a body must not be torn apart on ';' (that would split
5453 # "while C; do B; done" into unusable fragments); the caller keeps it
5454 # as one line so _run_lines()'s inline-control handling parses it.
5455 # Quotes, $(...), `...` and ${...} are skipped so a keyword appearing
5456 # only inside them (echo "done", VAR=$(case ...)) does not count.
5457 # Perl 5.005_03 compatible: character scan, no regex features beyond
5458 # \A and \b.
5459 # ----------------------------------------------------------------
5460 sub _inline_body_has_control {
5461 my ($body) = @_;
5462 return 0 unless defined $body && $body =~ /\S/;
5463 my @c = split //, $body;
5464 my $n = scalar @c;
5465 my $in_sq = 0; my $in_dq = 0; my $in_bt = 0;
5466 my $pdep = 0; my $bdep = 0;
5467 my $i = 0;
5468 my $cmd_pos = 1;
5469 while ($i < $n) {
5470 my $ch = $c[$i];
5471 if ($in_sq) { $in_sq = 0 if $ch eq "'"; $i++; next }
5472 if ($ch eq "'" && !$in_dq && !$in_bt) { $in_sq = 1; $cmd_pos = 0; $i++; next }
5473 if ($ch eq '"' && !$in_bt) { $in_dq = !$in_dq; $cmd_pos = 0; $i++; next }
5474 if ($ch eq '\\') { $i += 2; $cmd_pos = 0; next }
5475 if ($ch eq '`') { $in_bt = !$in_bt; $cmd_pos = 0; $i++; next }
5476 if (!$in_dq && !$in_bt) {
5477 if ($ch eq '$' && $i+1 < $n && $c[$i+1] eq '{') { $bdep++; $i += 2; $cmd_pos = 0; next }
5478 if ($bdep > 0 && $ch eq '}') { $bdep--; $i++; next }
5479 if ($ch eq '$' && $i+1 < $n && $c[$i+1] eq '(') { $pdep++; $i += 2; $cmd_pos = 0; next }
5480 if ($ch eq '(') { $pdep++; $i++; $cmd_pos = 1; next }
5481 if ($ch eq ')' && $pdep > 0) { $pdep--; $i++; next }
5482 }
5483 if (!$in_dq && !$in_bt && $pdep == 0 && $bdep == 0) {
5484 if ($ch eq ';') { $cmd_pos = 1; $i++; next }
5485 if ($ch eq '&' && $i+1 < $n && $c[$i+1] eq '&') { $cmd_pos = 1; $i += 2; next }
5486 if ($ch eq '|' && $i+1 < $n && $c[$i+1] eq '|') { $cmd_pos = 1; $i += 2; next }
5487 if ($ch eq '|') { $cmd_pos = 1; $i++; next }
5488 if ($ch eq '&') { $cmd_pos = 1; $i++; next }
5489 if ($ch =~ /\s/) { $i++; next }
5490 if ($cmd_pos) {
5491 my $tail = join('', @c[$i .. $n-1]);
5492 if ($tail =~ /\A(?:if|for|while|until|case|select)\b/i) {
5493 return 1;
5494 }
5495 }
5496 $cmd_pos = 0; $i++; next;
5497 }
5498 $i++;
5499 }
5500 return 0;
5501 }
5502  
5503 # ----------------------------------------------------------------
5504 # _parse_function: parse "name() {" or "function name {" blocks
5505 # Returns ($status, $new_i).
5506 # ----------------------------------------------------------------
5507 sub _parse_function {
5508 my ($class, $lines_ref, $start, $opts_ref) = @_;
5509 my @lines = @{$lines_ref};
5510 my $line = $lines[$start];
5511 $line =~ s/\r?\n\z//;
5512 $line =~ s/\A\s+//;
5513  
5514 my $name = '';
5515 if ($line =~ /\A([A-Za-z_][A-Za-z0-9_]*)\s*\(\s*\)\s*(?:\{.*)?\z/) {
5516 $name = $1;
5517 }
5518 elsif ($line =~ /\Afunction\s+([A-Za-z_][A-Za-z0-9_]*)\s*(?:\(\s*\))?\s*(?:\{.*)?\z/i) {
5519 $name = $1;
5520 }
5521 else {
5522 return (0, $start + 1);
5523 }
5524  
5525 my @body;
5526 my $depth = ($line =~ /\{/) ? 1 : 0;
5527 my $i = $start + 1;
5528  
5529 # Check if the function body is on the same line as the definition
5530 # e.g. "name() { cmd1; cmd2; }"
5531 if ($depth >= 1 && $line =~ /\{(.*)\}\s*\z/s) {
5532 my $inline = $1;
5533 $inline =~ s/\A\s+//; $inline =~ s/\s+\z//;
5534 # A trailing ';' just before the closing brace (name() { ...; })
5535 # is an empty separator; drop it so an inline control structure's
5536 # "; done"/"; fi"/"; esac" terminator sits at end-of-string where
5537 # the block parsers expect it.
5538 $inline =~ s/;\s*\z//;
5539 $inline =~ s/\s+\z//;
5540 # A naive split on ';' is correct for a body of simple commands
5541 # (name() { cmd1; cmd2; }) but WRONG for an inline control
5542 # structure: "while C; do B; done" would be torn into the four
5543 # pieces "while C" / "do B" / ... / "done", and the reassembled
5544 # multi-line form ("do" glued to a command on one line) is not a
5545 # shape the block parsers accept, so the loop silently ran
5546 # nothing. When the inline body contains a control-structure
5547 # keyword in command position, keep it as a SINGLE body line and
5548 # let _run_lines() apply the same inline-control handling it uses
5549 # for a control structure typed directly on one physical line
5550 # (this also drives the "prefix; control" split via
5551 # _find_control_split, so "cmd; while ...; do ...; done" works).
5552 if (_inline_body_has_control($inline)) {
5553 push @body, $inline if $inline =~ /\S/;
5554 }
5555 else {
5556 # Split on ; to get individual commands
5557 for my $part (split /;/, $inline) {
5558 $part =~ s/\A\s+//; $part =~ s/\s+\z//;
5559 push @body, $part if $part =~ /\S/;
5560 }
5561 }
5562 $_SH_FUNCTIONS{$name} = [ @body ];
5563 return (0, $i);
5564 }
5565  
5566 if ($depth == 0) {
5567 while ($i <= $#lines) {
5568 my $l = $lines[$i]; $l =~ s/\r?\n\z//; $l =~ s/\A\s+//;
5569 $i++;
5570 if ($l =~ /\{/) { $depth = 1; last }
5571 }
5572 }
5573  
5574 while ($i <= $#lines) {
5575 my $l = $lines[$i]; $l =~ s/\r?\n\z//;
5576 $i++;
5577 my $opens = () = ($l =~ /\{/g);
5578 my $closes = () = ($l =~ /\}/g);
5579 $depth += $opens - $closes;
5580 if ($depth <= 0) {
5581 my $before = $l;
5582 $before =~ s/\}\s*\z//;
5583 push @body, $before if $before =~ /\S/;
5584 last;
5585 }
5586 push @body, $l;
5587 }
5588  
5589 $_SH_FUNCTIONS{$name} = [ @body ];
5590 return (0, $i);
5591 }
5592  
5593 # ----------------------------------------------------------------
5594 # _call_sh_function: execute a registered SH function
5595 # ----------------------------------------------------------------
5596 sub _call_sh_function {
5597 my ($class, $name, $args_str, $opts_ref) = @_;
5598 return 1 unless exists $_SH_FUNCTIONS{$name};
5599  
5600 my @args = _parse_args($args_str);
5601  
5602 my @saved_arg;
5603 for my $n (1 .. 9) {
5604 push @saved_arg, BATsh::Env->get("BATSH_ARG$n");
5605 BATsh::Env->set("BATSH_ARG$n",
5606 defined($args[$n-1]) ? $args[$n-1] : '');
5607 }
5608 my @saved_pct;
5609 for my $n (1 .. 9) {
5610 push @saved_pct, BATsh::Env->get("%$n");
5611 BATsh::Env->set("%$n", defined($args[$n-1]) ? $args[$n-1] : '');
5612 }
5613 my $saved_star = BATsh::Env->get('%*');
5614 BATsh::Env->set('%*', join(' ', @args));
5615  
5616 push @FUNCTION_STACK, {};
5617 my $saved_ret = $_RETURN;
5618 $_RETURN = 0;
5619  
5620 my $rc = _run_lines($class, $_SH_FUNCTIONS{$name}, $opts_ref);
5621  
5622 $_RETURN = $saved_ret;
5623  
5624 # Restore local variables saved in this function's scope
5625 if (@FUNCTION_STACK) {
5626 my $frame = $FUNCTION_STACK[-1];
5627 for my $var (keys %{$frame}) {
5628 my $old = $frame->{$var};
5629 if (defined $old) { BATsh::Env->set($var, $old) }
5630 else { BATsh::Env->unset($var) }
5631 }
5632 }
5633 pop @FUNCTION_STACK;
5634  
5635 for my $n (1 .. 9) {
5636 my $v = $saved_arg[$n-1];
5637 BATsh::Env->set("BATSH_ARG$n", defined $v ? $v : '');
5638 }
5639 for my $n (1 .. 9) {
5640 my $v = $saved_pct[$n-1];
5641 BATsh::Env->set("%$n", defined $v ? $v : '');
5642 }
5643 BATsh::Env->set('%*', defined $saved_star ? $saved_star : '');
5644  
5645 $LAST_STATUS = $rc;
5646 return $rc;
5647 }
5648  
5649 # ----------------------------------------------------------------
5650 # _parse_args: split a string into arguments respecting quotes
5651 # ----------------------------------------------------------------
5652 sub _parse_args {
5653 # $protect_quoted is set by a caller that joins the words back into a
5654 # string and hands that string to a builtin which dequotes it again.
5655 # The quotes are gone by then, so a backslash that was INSIDE them
5656 # would be read as an escape by that second pass and disappear:
5657 # echo "C:\dir"/*.txt printed C:dir/*.txt. Protecting it marks it as
5658 # data, exactly as an expansion result is marked, while a backslash
5659 # written outside quotes stays an escape, as in bash.
5660 my ($str, $protect_quoted) = @_;
5661 $str = '' unless defined $str;
5662 $str =~ s/\A\s+//; $str =~ s/\s+\z//;
5663 return () unless $str =~ /\S/;
5664 my @args;
5665 my @quoted; # parallel array: 1 if word was quoted, 0 if bare
5666 my $cur = '';
5667 my $word_quoted = 0;
5668 my $in_sq = 0;
5669 my $in_dq = 0;
5670 for my $ch (split //, $str) {
5671 if ($in_sq) {
5672 if ($ch eq "'") { $in_sq = 0 }
5673 else {
5674 $cur .= $protect_quoted ? _protect_lit($ch) : $ch;
5675 $word_quoted = 1;
5676 }
5677 next;
5678 }
5679 if ($ch eq "'" && !$in_dq) { $in_sq = 1; $word_quoted = 1; next }
5680 if ($ch eq '"' && !$in_sq) { $in_dq = !$in_dq; $word_quoted = 1; next }
5681 if ($ch =~ /\s/ && !$in_sq && !$in_dq) {
5682 push @args, $cur;
5683 push @quoted, $word_quoted;
5684 $cur = ''; $word_quoted = 0;
5685 next;
5686 }
5687 $cur .= ($protect_quoted && $in_dq) ? _protect_lit($ch) : $ch;
5688 }
5689 push @args, $cur if $cur ne '' || @args;
5690 push @quoted, $word_quoted if $cur ne '' || @quoted;
5691 # Apply filename globbing to unquoted words containing metacharacters
5692 my @result;
5693 for my $i (0 .. $#args) {
5694 if (!$quoted[$i] && $args[$i] =~ /[*?\[]/) {
5695 push @result, _glob_expand($args[$i]);
5696 }
5697 else {
5698 push @result, $args[$i];
5699 }
5700 }
5701 return @result;
5702 }
5703  
5704 # ----------------------------------------------------------------
5705 # ----------------------------------------------------------------
5706 sub _cmd_external {
5707 my ($cmd, $rest) = @_;
5708 $rest = '' unless defined $rest;
5709 $rest =~ s/\A\s+//;
5710 my $full = $rest ne '' ? "$cmd $rest" : $cmd;
5711 # The command line goes to the OS verbatim, so a protected backslash
5712 # has to be a real backslash again here.
5713 $full = _unprotect_lit($full);
5714 $full = BATsh::MB::dec($full);
5715 BATsh::Env->sync_to_env();
5716 my $rc = system($full);
5717 if ($rc == -1) {
5718 # system() could not launch the command (not found / exec failed).
5719 # bash reports 127 for "command not found"; without this guard the
5720 # old ($rc >> 8) arithmetic on -1 produced a huge garbage status.
5721 $LAST_STATUS = 127;
5722 }
5723 else {
5724 $LAST_STATUS = ($rc == 0) ? 0 : (($rc >> 8) || 1);
5725 }
5726 return $LAST_STATUS;
5727 }
5728  
5729 # ----------------------------------------------------------------
5730 # let / type / command (v0.08)
5731 # ----------------------------------------------------------------
5732 # Prior to v0.08 these three POSIX/bash builtins fell through to the
5733 # external-command path and were handed to whatever real shell (if any)
5734 # happened to exist -- which failed on systems without that shell, and
5735 # defeated BATsh's "no external shell required" design. They are now
5736 # evaluated internally in pure Perl.
5737  
5738 # let EXPR [EXPR ...]
5739 # Each argument is evaluated as a shell-arithmetic expression (reusing
5740 # _eval_arith, so assignments and ++/-- write back to the variable store).
5741 # The exit status is 0 when the LAST expression is non-zero, else 1 --
5742 # the inverse-of-truth convention bash's "let" and "(( ))" both use.
5743 # Arguments are quote-stripped but NOT filename-globbed, so `let "x=1*2"`
5744 # and `let x=1+2` both behave as arithmetic rather than pathname patterns.
5745 sub _cmd_let {
5746 my ($rest) = @_;
5747 $rest = '' unless defined $rest;
5748 my @exprs = map { _arr_dequote($_) } _arr_split_words($rest);
5749 if (!@exprs) {
5750 print STDERR "sh: let: expression expected\n";
5751 $LAST_STATUS = 1;
5752 return 1;
5753 }
5754 my $last = 0;
5755 for my $e (@exprs) {
5756 $last = _eval_arith($e);
5757 }
5758 $LAST_STATUS = ($last != 0) ? 0 : 1;
5759 return $LAST_STATUS;
5760 }
5761  
5762 # _sh_name_kind(NAME): classify NAME the way "type" / "command -v" do,
5763 # in bash's precedence order (alias, keyword, function, builtin, file).
5764 # Returns (KIND, DETAIL) where KIND is one of
5765 # 'alias' (DETAIL = alias body), 'keyword', 'function', 'builtin',
5766 # 'file' (DETAIL = resolved path), or '' (not found; DETAIL undef).
5767 sub _sh_name_kind {
5768 my ($name) = @_;
5769 return ('', undef) unless defined $name && $name ne '';
5770  
5771 return ('alias', $_SH_ALIAS{$name}) if exists $_SH_ALIAS{$name};
5772  
5773 my $lc = lc($name);
5774 my %kw = map { ($_ => 1) } qw(
5775 if then else elif fi for while until do done
5776 case esac function in select time
5777 );
5778 return ('keyword', undef) if $kw{$lc};
5779  
5780 return ('function', undef) if exists $_SH_FUNCTIONS{$name};
5781  
5782 return ('builtin', undef) if $name eq '[' || $name eq ':' || $name eq '.';
5783 my %bi = map { ($_ => 1) } qw(
5784 alias break cd command continue declare echo eval exec exit export
5785 false getopts hash let local mapfile printf pwd read readarray
5786 readonly return set shift shopt source test true trap type typeset
5787 umask unalias unset
5788 );
5789 return ('builtin', undef) if $bi{$lc};
5790  
5791 my $path = _sh_find_on_path($name);
5792 return ('file', $path) if defined $path;
5793  
5794 return ('', undef);
5795 }
5796  
5797 # _sh_find_on_path(NAME): locate an executable NAME the way a shell would.
5798 # A NAME containing a directory separator is tested directly; otherwise each
5799 # PATH element is searched (';'-separated and PATHEXT-aware on Windows-like
5800 # systems, ':'-separated and -x-tested elsewhere). Returns the full path,
5801 # or undef when not found. Pure-Perl and Perl 5.005_03 safe.
5802 sub _sh_find_on_path {
5803 my ($name) = @_;
5804 return undef unless defined $name && $name ne '';
5805 my $is_win = ($^O =~ /MSWin32|dos|os2|cygwin/i) ? 1 : 0;
5806  
5807 if ($name =~ m{[/\\]}) {
5808 return $name if -f $name && ($is_win || -x $name);
5809 return undef;
5810 }
5811  
5812 my $path = BATsh::Env->get('PATH');
5813 $path = $ENV{'PATH'} unless defined $path && $path ne '';
5814 return undef unless defined $path && $path ne '';
5815  
5816 my $sep = $is_win ? ';' : ':';
5817 my @exts = ('');
5818 if ($is_win) {
5819 my $pe = BATsh::Env->get('PATHEXT');
5820 $pe = $ENV{'PATHEXT'} unless defined $pe && $pe ne '';
5821 $pe = '.COM;.EXE;.BAT;.CMD' unless defined $pe && $pe ne '';
5822 push @exts, split(/;/, $pe);
5823 }
5824  
5825 my @dirs = split(/\Q$sep\E/, $path);
5826 for my $dir (@dirs) {
5827 $dir = '.' if $dir eq '';
5828 for my $ext (@exts) {
5829 my $cand = File::Spec->catfile($dir, $name . $ext);
5830 if ($is_win) {
5831 return $cand if -f $cand;
5832 }
5833 else {
5834 return $cand if -f $cand && -x $cand;
5835 }
5836 }
5837 }
5838 return undef;
5839 }
5840  
5841 # _print_type_verbose(NAME, KIND, DETAIL): emit the "type NAME" / "command -V
5842 # NAME" description line. Returns 1 when found, 0 (with a STDERR diagnostic)
5843 # when NAME is unknown.
5844 sub _print_type_verbose {
5845 my ($name, $kind, $detail) = @_;
5846 if ($kind eq 'alias') {
5847 print "$name is aliased to `" . (defined $detail ? $detail : '') . "'\n";
5848 }
5849 elsif ($kind eq 'keyword') { print "$name is a shell keyword\n" }
5850 elsif ($kind eq 'function') { print "$name is a function\n" }
5851 elsif ($kind eq 'builtin') { print "$name is a shell builtin\n" }
5852 elsif ($kind eq 'file') { print "$name is $detail\n" }
5853 else {
5854 print STDERR "sh: type: $name: not found\n";
5855 return 0;
5856 }
5857 return 1;
5858 }
5859  
5860 # type [-t|-p|-a] NAME [NAME ...]
5861 # Default: describe how each NAME would be interpreted.
5862 # -t: print only the one-word kind (alias/keyword/function/builtin/file).
5863 # -p: print only the path when NAME is an external file (else nothing).
5864 # -a: describe all matches (this interpreter reports the single primary
5865 # match, so -a behaves like the default form).
5866 # Exit status is non-zero when any NAME is not found.
5867 sub _cmd_type {
5868 my ($rest) = @_;
5869 $rest = '' unless defined $rest;
5870 my @w = map { _arr_dequote($_) } _arr_split_words($rest);
5871  
5872 my $mode = ''; # '', 't', 'p', 'a'
5873 while (@w && $w[0] =~ /\A-[atpP]+\z/) {
5874 my $opt = shift @w;
5875 $mode = 'a' if $opt =~ /a/;
5876 $mode = 't' if $opt =~ /t/;
5877 $mode = 'p' if $opt =~ /[pP]/;
5878 }
5879 if (!@w) { $LAST_STATUS = 0; return 0 }
5880  
5881 my $status = 0;
5882 for my $name (@w) {
5883 my ($kind, $detail) = _sh_name_kind($name);
5884 if ($mode eq 't') {
5885 if ($kind eq '') { $status = 1 }
5886 else { print $kind, "\n" }
5887 }
5888 elsif ($mode eq 'p') {
5889 if ($kind eq 'file') { print $detail, "\n" }
5890 elsif ($kind eq '') { $status = 1 }
5891 # builtin/function/keyword/alias: print nothing (bash -p)
5892 }
5893 else {
5894 _print_type_verbose($name, $kind, $detail) or $status = 1;
5895 }
5896 }
5897 $LAST_STATUS = $status;
5898 return $status;
5899 }
5900  
5901 # command [-p] [-v|-V] NAME [ARG ...]
5902 # -v: print how NAME would be invoked (name for a builtin/function/keyword,
5903 # "alias NAME='...'" for an alias, full path for an external file);
5904 # exit non-zero if NAME is not found -- the ubiquitous feature-detection
5905 # idiom `if command -v foo >/dev/null; then ...`.
5906 # -V: verbose description, like "type NAME".
5907 # plain: run NAME bypassing any shell function of that name.
5908 # -p is accepted and ignored (PATH is always searched).
5909 sub _cmd_command {
5910 my ($class, $rest, $raw_pre, $opts_ref) = @_;
5911 $rest = '' unless defined $rest;
5912 my @w = map { _arr_dequote($_) } _arr_split_words($rest);
5913  
5914 my $mode = ''; # '', 'v', 'V'
5915 while (@w && $w[0] =~ /\A-[pvV]+\z/) {
5916 my $opt = shift @w;
5917 $mode = 'v' if $opt =~ /v/;
5918 $mode = 'V' if $opt =~ /V/;
5919 # -p: accepted, no effect
5920 }
5921 # A bare "--" ends option parsing.
5922 shift @w if @w && $w[0] eq '--';
5923  
5924 if (!@w) { $LAST_STATUS = ($mode ne '') ? 1 : 0; return $LAST_STATUS }
5925  
5926 if ($mode eq 'v' || $mode eq 'V') {
5927 my $status = 0;
5928 for my $name (@w) {
5929 my ($kind, $detail) = _sh_name_kind($name);
5930 if ($mode eq 'V') {
5931 _print_type_verbose($name, $kind, $detail) or $status = 1;
5932 }
5933 else { # -v
5934 if ($kind eq 'alias') { print "alias $name='" . (defined $detail ? $detail : '') . "'\n" }
5935 elsif ($kind eq 'file') { print $detail, "\n" }
5936 elsif ($kind eq '') { $status = 1 }
5937 else { print $name, "\n" } # keyword/function/builtin
5938 }
5939 }
5940 $LAST_STATUS = $status;
5941 return $status;
5942 }
5943  
5944 # Plain run form: re-dispatch the raw remainder with function lookup
5945 # suppressed. Recover the text after the leading "command" word (and any
5946 # -p / -- options) from the pre-expansion source so _expand() runs once.
5947 my $raw = defined $raw_pre ? $raw_pre : $rest;
5948 $raw =~ s/\A\s*//;
5949 $raw =~ s/\A[Cc][Oo][Mm][Mm][Aa][Nn][Dd]\b//;
5950 $raw =~ s/\A\s+//;
5951 while ($raw =~ /\A(-[pvV]+|--)\s/) {
5952 my $tok = $1;
5953 $raw =~ s/\A(?:-[pvV]+|--)\s+//;
5954 last if $tok eq '--';
5955 }
5956 local $_CMD_NO_FUNC = 1;
5957 return _exec_line($class, $raw, $opts_ref);
5958 }
5959  
5960 # ----------------------------------------------------------------
5961 # Background execution helpers (v1)
5962 # ----------------------------------------------------------------
5963 # ----------------------------------------------------------------
5964 # umask / hash / readonly / mapfile (v0.08)
5965 # ----------------------------------------------------------------
5966 # _sh_is_readonly(NAME): true when NAME carries the readonly attribute.
5967 sub _sh_is_readonly {
5968 my ($name) = @_;
5969 return 0 unless defined $name;
5970 return $_SH_READONLY{ uc($name) } ? 1 : 0;
5971 }
5972  
5973 # _sh_store_scalar(NAME, VALUE): the single choke point for a plain scalar
5974 # assignment. Honours the readonly attribute (refused, status source
5975 # returns 0) and the integer attribute (VALUE evaluated as arithmetic).
5976 # Returns 1 when the value was stored, 0 when a readonly variable blocked
5977 # it. All the ordinary assignment paths (VAR=val, prefix VAR=val cmd,
5978 # export VAR=val) funnel through here so the attributes are enforced
5979 # uniformly.
5980 sub _sh_store_scalar {
5981 my ($name, $val) = @_;
5982 $val = _unprotect_lit($val) if defined $val;
5983 my $ik = uc($name);
5984 if ($_SH_READONLY{$ik}) {
5985 print STDERR "sh: $name: readonly variable\n";
5986 return 0;
5987 }
5988 if ($_SH_INTATTR{$ik}) {
5989 $val = _eval_arith(defined $val ? $val : '');
5990 }
5991 BATsh::Env->set($name, $val);
5992 return 1;
5993 }
5994  
5995 # umask [-S] [MODE]
5996 # With no MODE, print the current file-creation mask (octal, or symbolic
5997 # with -S). A numeric (octal) MODE sets the mask. Uses Perl's umask, so
5998 # it is a genuine process mask on Unix-like systems (a no-op reflecting
5999 # whatever the C library reports on Win32).
6000 sub _cmd_umask {
6001 my ($rest) = @_;
6002 $rest = '' unless defined $rest;
6003 $rest =~ s/\A\s+//; $rest =~ s/\s+\z//;
6004  
6005 # Seed the shell mask from the real process umask on first use.
6006 if (!$_SH_UMASK_INIT) {
6007 my $u = umask();
6008 $_SH_UMASK = defined $u ? $u : 0;
6009 $_SH_UMASK_INIT = 1;
6010 }
6011  
6012 my $symbolic = 0;
6013 if ($rest =~ s/\A-S\b\s*//) { $symbolic = 1 }
6014  
6015 if ($rest eq '') {
6016 if ($symbolic) { print _umask_symbolic($_SH_UMASK), "\n" }
6017 else { printf "%04o\n", $_SH_UMASK }
6018 $LAST_STATUS = 0;
6019 return 0;
6020 }
6021 if ($rest =~ /\A[0-7]+\z/) {
6022 $_SH_UMASK = oct($rest) & 0777;
6023 umask($_SH_UMASK); # honoured on Unix, harmless where it is not
6024 $LAST_STATUS = 0;
6025 return 0;
6026 }
6027 # Symbolic mode: "u=rwx,g=rx,o=rx" (and +/- ops). The operand names the
6028 # permissions to LEAVE enabled; the mask is their complement.
6029 my $sym = _umask_apply_symbolic($_SH_UMASK, $rest);
6030 if (defined $sym) {
6031 $_SH_UMASK = $sym;
6032 umask($_SH_UMASK);
6033 $LAST_STATUS = 0;
6034 return 0;
6035 }
6036 print STDERR "sh: umask: $rest: invalid mask\n";
6037 $LAST_STATUS = 1;
6038 return 1;
6039 }
6040  
6041 # _umask_apply_symbolic(MASK, SPEC): apply a chmod-style symbolic SPEC
6042 # ("[ugoa]*[-+=][rwx]*", comma-separated) to the numeric umask MASK, in
6043 # terms of the permissions the mask leaves ENABLED. Returns the new
6044 # numeric mask, or undef when SPEC is not valid symbolic syntax.
6045 sub _umask_apply_symbolic {
6046 my ($mask, $spec) = @_;
6047 return undef unless defined $spec && $spec ne '';
6048 my @allow = (
6049 (~ (($mask >> 6) & 7)) & 7,
6050 (~ (($mask >> 3) & 7)) & 7,
6051 (~ ($mask & 7)) & 7,
6052 );
6053 my %idx = ('u' => 0, 'g' => 1, 'o' => 2);
6054 for my $clause (split /,/, $spec) {
6055 return undef unless $clause =~ /\A([ugoa]*)([-+=])([rwx]*)\z/;
6056 my ($who, $op, $pstr) = ($1, $2, $3);
6057 my $perm = 0;
6058 $perm |= 4 if $pstr =~ /r/;
6059 $perm |= 2 if $pstr =~ /w/;
6060 $perm |= 1 if $pstr =~ /x/;
6061 my @classes;
6062 if ($who eq '' || $who =~ /a/) { @classes = (0, 1, 2) }
6063 else {
6064 for my $w (split //, $who) { push @classes, $idx{$w} }
6065 }
6066 for my $ci (@classes) {
6067 if ($op eq '=') { $allow[$ci] = $perm }
6068 elsif ($op eq '+') { $allow[$ci] |= $perm }
6069 else { $allow[$ci] &= (~ $perm) & 7 }
6070 }
6071 }
6072 my $newmask = 0;
6073 $newmask |= ((~ $allow[0]) & 7) << 6;
6074 $newmask |= ((~ $allow[1]) & 7) << 3;
6075 $newmask |= (~ $allow[2]) & 7;
6076 return $newmask & 0777;
6077 }
6078  
6079 # _umask_symbolic(MASK): render a numeric umask as the bash-style symbolic
6080 # form "u=rwx,g=rx,o=rx" (the permissions the mask LEAVES enabled).
6081 sub _umask_symbolic {
6082 my ($mask) = @_;
6083 my @cls = ('u', 'g', 'o');
6084 my @sh = (($mask >> 6) & 7, ($mask >> 3) & 7, $mask & 7);
6085 my @out;
6086 for my $i (0 .. 2) {
6087 my $allow = (~ $sh[$i]) & 7;
6088 my $s = '';
6089 $s .= 'r' if $allow & 4;
6090 $s .= 'w' if $allow & 2;
6091 $s .= 'x' if $allow & 1;
6092 push @out, $cls[$i] . '=' . $s;
6093 }
6094 return join(',', @out);
6095 }
6096  
6097 # hash [-r] [-l] [-t] [-d name] [-p path name] [NAME ...]
6098 # BATsh resolves commands through PATH on every call and keeps no
6099 # location cache, so the maintenance forms (-r clear, -l/-t list, -d/-p)
6100 # are accepted as successful no-ops. "hash NAME ..." verifies each NAME
6101 # is found on PATH (status 1 if any is missing), matching the observable
6102 # result of bash caching a lookup.
6103 sub _cmd_hash {
6104 my ($rest) = @_;
6105 $rest = '' unless defined $rest;
6106 $rest =~ s/\A\s+//; $rest =~ s/\s+\z//;
6107 return _sh_set_status(0) if $rest eq '';
6108 return _sh_set_status(0) if $rest =~ /\A-[rlt]\b\s*\z/;
6109 return _sh_set_status(0) if $rest =~ /\A-[dp]\b/;
6110  
6111 my @tok = map { _arr_dequote($_) } _arr_split_words($rest);
6112 my $status = 0;
6113 for my $name (@tok) {
6114 next if $name =~ /\A-/;
6115 if (!defined _sh_find_on_path($name)) {
6116 print STDERR "sh: hash: $name: not found\n";
6117 $status = 1;
6118 }
6119 }
6120 return _sh_set_status($status);
6121 }
6122  
6123 sub _sh_set_status {
6124 my ($s) = @_;
6125 $LAST_STATUS = $s;
6126 return $s;
6127 }
6128  
6129 # readonly [-p] [NAME[=VALUE] ...]
6130 # Mark each NAME read-only (optionally assigning VALUE first). With no
6131 # NAME, or with -p, list the current readonly variables in a form that
6132 # can be re-read.
6133 sub _cmd_readonly {
6134 my ($class, $rest) = @_;
6135 $rest = '' unless defined $rest;
6136 $rest =~ s/\A\s+//; $rest =~ s/\s+\z//;
6137  
6138 if ($rest eq '' || $rest eq '-p') {
6139 for my $ik (sort keys %_SH_READONLY) {
6140 my $v = BATsh::Env->get($ik);
6141 $v = '' unless defined $v;
6142 $v =~ s/'/'\\''/g;
6143 print "readonly $ik='$v'\n";
6144 }
6145 return _sh_set_status(0);
6146 }
6147  
6148 my @tok = map { _arr_dequote($_) } _arr_split_words($rest);
6149 my $status = 0;
6150 for my $t (@tok) {
6151 next if $t eq '-p' || $t eq '';
6152 if ($t =~ /\A([A-Za-z_][A-Za-z0-9_]*)=(.*)\z/s) {
6153 my ($name, $val) = ($1, $2);
6154 if (_sh_is_readonly($name)) {
6155 print STDERR "sh: $name: readonly variable\n";
6156 $status = 1;
6157 next;
6158 }
6159 BATsh::Env->set($name, $val);
6160 $_SH_READONLY{ uc($name) } = 1;
6161 }
6162 elsif ($t =~ /\A([A-Za-z_][A-Za-z0-9_]*)\z/) {
6163 $_SH_READONLY{ uc($1) } = 1;
6164 }
6165 }
6166 return _sh_set_status($status);
6167 }
6168  
6169 # mapfile / readarray [-t] [-d DELIM] [-n COUNT] [-O ORIGIN] [-s SKIP] [ARRAY]
6170 # Read lines from standard input into the indexed array ARRAY (default
6171 # MAPFILE). -t strips the trailing delimiter from each line; -d sets the
6172 # line delimiter (default newline); -n COUNT copies at most COUNT lines
6173 # (0 = all); -s SKIP discards the first SKIP lines; -O ORIGIN stores the
6174 # first line at index ORIGIN. STDIN is whatever the surrounding
6175 # redirection supplied (e.g. "mapfile arr < file").
6176 sub _cmd_mapfile {
6177 my ($class, $rest) = @_;
6178 $rest = '' unless defined $rest;
6179 my @tok = map { _arr_dequote($_) } _arr_split_words($rest);
6180  
6181 my $strip = 0;
6182 my $delim = "\n";
6183 my $count = 0; # 0 = unlimited
6184 my $skip = 0;
6185 my $origin = 0;
6186 while (@tok) {
6187 my $t = $tok[0];
6188 if ($t eq '-t') { shift @tok; $strip = 1 }
6189 elsif ($t eq '-n') { shift @tok; $count = @tok ? int(_arr_num(shift @tok)) : 0 }
6190 elsif ($t eq '-s') { shift @tok; $skip = @tok ? int(_arr_num(shift @tok)) : 0 }
6191 elsif ($t eq '-O') { shift @tok; $origin = @tok ? int(_arr_num(shift @tok)) : 0 }
6192 elsif ($t eq '-d') { shift @tok; $delim = @tok ? shift @tok : "\n" }
6193 elsif ($t =~ /\A-d(.+)\z/s) { shift @tok; $delim = $1 }
6194 elsif ($t eq '-u' || $t eq '-c' || $t eq '-C') { shift @tok; shift @tok if @tok }
6195 elsif ($t =~ /\A-/) { shift @tok } # unknown flag: ignore
6196 else { last }
6197 }
6198 my $name = @tok ? shift @tok : 'MAPFILE';
6199 $name = 'MAPFILE' unless defined $name && $name ne '';
6200  
6201 my $sep = (defined $delim && length $delim) ? substr($delim, 0, 1) : "\n";
6202 my @lines;
6203 {
6204 local $/ = $sep;
6205 while (defined(my $l = <STDIN>)) { push @lines, $l }
6206 }
6207  
6208 if ($skip > 0) {
6209 if ($skip >= @lines) { @lines = () }
6210 else { splice(@lines, 0, $skip) }
6211 }
6212 if ($count > 0 && @lines > $count) { @lines = @lines[0 .. $count - 1] }
6213 if ($strip) { for my $l (@lines) { $l =~ s/\Q$sep\E\z// } }
6214 @lines = map { BATsh::MB::enc($_) } @lines;
6215  
6216 my $k = _arr_name($name);
6217 $_SH_ARRAY{$k} = {};
6218 $_SH_ARRAY_TYPE{$k} = 'indexed';
6219 BATsh::Env->unset($name);
6220 my $ix = $origin;
6221 for my $l (@lines) { $_SH_ARRAY{$k}{$ix} = $l; $ix++ }
6222  
6223 return _sh_set_status(0);
6224 }
6225  
6226 # _arr_num(S): integer value of a leading numeric prefix (0 otherwise).
6227 sub _arr_num {
6228 my ($s) = @_;
6229 $s = '' unless defined $s;
6230 return ($s =~ /\A\s*([-+]?\d+)/) ? int($1) : 0;
6231 }
6232  
6233  
6234 # Rules:
6235 # * only the last non-space character may be the background &
6236 # * it must not be part of && (i.e. preceding char must not be &)
6237 # * it must not be an fd-duplication >& (preceding char must not be >)
6238 # * it must be outside single/double quotes
6239 # * the remaining command must be non-empty
6240 sub _split_trailing_bg {
6241 my ($line) = @_;
6242 return (0, $line) unless defined $line;
6243  
6244 # Find the index of the last character, ignoring trailing whitespace.
6245 my $rtrim = $line;
6246 $rtrim =~ s/\s+\z//;
6247 return (0, $line) if $rtrim eq '';
6248  
6249 my @chars = split //, $rtrim;
6250 my $last = $#chars;
6251 return (0, $line) unless $chars[$last] eq '&';
6252  
6253 # && is a compound operator, not background.
6254 return (0, $line) if $last >= 1 && $chars[$last-1] eq '&';
6255 # >& is fd duplication, not background.
6256 return (0, $line) if $last >= 1 && $chars[$last-1] eq '>';
6257  
6258 # Verify the trailing & is outside quotes and not backslash-escaped by
6259 # scanning up to it. $esc_last becomes true if the char at $last is
6260 # escaped by an immediately preceding (unquoted) backslash.
6261 my $in_sq = 0;
6262 my $in_dq = 0;
6263 my $esc_last = 0;
6264 my $i = 0;
6265 while ($i < $last) {
6266 my $ch = $chars[$i];
6267 if ($in_sq) {
6268 $in_sq = 0 if $ch eq "'";
6269 $i++; next;
6270 }
6271 if ($ch eq '\\' && !$in_sq) { # backslash escapes next char
6272 $esc_last = 1 if $i + 1 == $last;
6273 $i += 2; next;
6274 }
6275 if ($ch eq "'" && !$in_dq) { $in_sq = 1; $i++; next }
6276 if ($ch eq '"' && !$in_sq) { $in_dq = !$in_dq; $i++; next }
6277 $i++;
6278 }
6279 return (0, $line) if $in_sq || $in_dq; # & is inside a quote
6280 return (0, $line) if $esc_last; # & is backslash-escaped
6281  
6282 # Strip the trailing & (and surrounding whitespace before it).
6283 my $stripped = join('', @chars[0 .. $last-1]);
6284 $stripped =~ s/\s+\z//;
6285 return (0, $line) if $stripped eq ''; # nothing to run
6286  
6287 return (1, $stripped);
6288 }
6289  
6290 # _sh_word_is_foreground: true when the first word of a backgrounded line
6291 # is a BATsh builtin, defined SH function, control keyword, or a variable
6292 # assignment. Such commands run in the foreground and the trailing &
6293 # is ignored (documented limitation: only external commands background).
6294 sub _sh_word_is_foreground {
6295 my ($w) = @_;
6296 return 0 unless defined $w && $w ne '';
6297  
6298 # VAR=value assignment
6299 return 1 if $w =~ /\A[A-Za-z_][A-Za-z0-9_]*=/;
6300  
6301 # test bracket and no-op
6302 return 1 if $w eq '[' || $w eq ':' || $w eq '.';
6303  
6304 my $lc = lc($w);
6305  
6306 my %builtin = (
6307 export => 1, unset => 1, echo => 1, printf => 1, cd => 1,
6308 pwd => 1, exit => 1, 'true' => 1, 'false' => 1, read => 1,
6309 test => 1, source => 1, 'return' => 1, 'break' => 1,
6310 'continue' => 1, shift => 1, local => 1, set => 1,
6311 let => 1, type => 1, command => 1,
6312 umask => 1, hash => 1, readonly => 1, mapfile => 1, readarray => 1,
6313 );
6314 return 1 if $builtin{$lc};
6315  
6316 # Control keywords (defensive; these are normally handled in _run_lines)
6317 my %kw = (
6318 'if' => 1, then => 1, 'else' => 1, elif => 1, fi => 1,
6319 'for' => 1, 'while' => 1, until => 1, 'do' => 1, done => 1,
6320 case => 1, esac => 1, function => 1, in => 1,
6321 );
6322 return 1 if $kw{$lc};
6323  
6324 # Defined SH function (case-sensitive, as in _exec_line dispatch)
6325 return 1 if exists $_SH_FUNCTIONS{$w};
6326  
6327 return 0;
6328 }
6329  
6330 # _bg_tempfile: create a unique, empty temp file (O_CREAT|O_EXCL to avoid
6331 # symlink races) for capturing a background job's PID on Unix-like systems.
6332 # Returns the path, or undef on failure.
6333 sub _bg_tempfile {
6334 my $dir = $ENV{'TMPDIR'} || $ENV{'TEMP'} || $ENV{'TMP'} || '';
6335 $dir = '/tmp' if $dir eq '' && -d '/tmp';
6336 $dir = '.' if $dir eq '';
6337 $dir =~ s{[\\/]+\z}{};
6338 $dir = '.' if !(-d $dir && -w $dir);
6339  
6340 my $attempt = 0;
6341 while ($attempt < 1000) {
6342 $_BG_SEQ++;
6343 $attempt++;
6344 my $path = $dir . '/' . 'batsh_bg_' . $$ . '_' . $_BG_SEQ;
6345 if (sysopen(_BG_TMP, $path, O_WRONLY | O_CREAT | O_EXCL, 0600)) {
6346 close(_BG_TMP);
6347 push @_BG_TMPFILES, $path;
6348 return $path;
6349 }
6350 # EEXIST or transient error: retry with next sequence number
6351 }
6352 warn "sh: cannot create background pidfile in $dir: $!\n";
6353 return undef;
6354 }
6355  
6356 # _bg_launch: start $cmdline asynchronously.
6357 # Win32 : system(1, STRING) spawns via the command shell (P_NOWAIT)
6358 # and returns the PID directly.
6359 # Unix-like : delegate to /bin/sh so the job is backgrounded without a
6360 # Perl fork; the shell's $! (the job PID) is written to a
6361 # temp file and read back into BATsh's own $!.
6362 # On a successful launch $? (LAST_STATUS) is 0; the exit code of the
6363 # background job itself is not awaited (sh semantics).
6364 # _bg_launch: un-guard the command line, then hand it to the platform-
6365 # specific spawner below (system(1,...) on Win32, "&" on POSIX).
6366 sub _bg_launch {
6367 my ($class, $cmdline) = @_;
6368 return _bg_launch_decoded($class, BATsh::MB::dec($cmdline));
6369 }
6370  
6371 sub _bg_launch_decoded {
6372 my ($class, $cmdline) = @_;
6373 $cmdline = '' unless defined $cmdline;
6374 return 0 if $cmdline =~ /\A\s*\z/;
6375 BATsh::Env->sync_to_env();
6376  
6377 if ($^O =~ /MSWin32/i) {
6378 my $pid = system(1, $cmdline);
6379 if (defined $pid && $pid > 0) {
6380 $_LAST_BG_PID = $pid;
6381 $LAST_STATUS = 0;
6382 }
6383 else {
6384 warn "sh: failed to start background process\n";
6385 $LAST_STATUS = 1;
6386 }
6387 return $LAST_STATUS;
6388 }
6389  
6390 # Unix-like
6391 my $pidfile = _bg_tempfile();
6392 my $rc;
6393 if (defined $pidfile) {
6394 # Group the command so that the whole list (pipelines, &&, ...) is
6395 # backgrounded as a unit, then echo the job PID ($!) to the file.
6396 $rc = system("{ $cmdline ; } & echo \$! > '$pidfile'");
6397 if (open(_BG_PIDFH, "< $pidfile")) {
6398 local $/;
6399 my $buf = <_BG_PIDFH>;
6400 close(_BG_PIDFH);
6401 $buf = '' unless defined $buf;
6402 my $pid = '';
6403 ($pid) = ($buf =~ /(\d+)/);
6404 $_LAST_BG_PID = $pid if defined $pid && $pid ne '';
6405 }
6406 unlink $pidfile;
6407 @_BG_TMPFILES = grep { $_ ne $pidfile } @_BG_TMPFILES;
6408 }
6409 else {
6410 $rc = system("{ $cmdline ; } &");
6411 }
6412 $LAST_STATUS = (defined $rc && $rc != -1) ? 0 : 1;
6413 return $LAST_STATUS;
6414 }
6415  
6416  
6417 # ----------------------------------------------------------------
6418 # Split "cmd rest" honouring quoted strings
6419 # ----------------------------------------------------------------
6420 sub _split_sh {
6421 my ($line) = @_;
6422 if ($line =~ /\A(\S+)\s*(.*)\z/s) {
6423 return ($1, $2);
6424 }
6425 return ($line, '');
6426 }
6427  
6428 # ----------------------------------------------------------------
6429 # _sh_assign_prefix: detect POSIX assignment prefixes on a RAW (un-expanded)
6430 # command line, e.g. `IFS= read -r LINE` or `LC_ALL=C sort file`.
6431 #
6432 # Parses one or more leading VAR=VALUE words, where VALUE is read with
6433 # quote / $(...) / backtick awareness so that an assignment whose value
6434 # merely *contains* spaces (e.g. UPPER=$(echo "a b")) is NOT mistaken for
6435 # a prefix followed by a command.
6436 #
6437 # Returns (\@pairs, $remainder):
6438 # - @pairs is a list of [VAR, RAW_VALUE] (value still un-expanded)
6439 # - $remainder is the rest of the line (the command to run), '' if none
6440 # Returns () when the line does not begin with an assignment.
6441 # ----------------------------------------------------------------
6442 sub _sh_assign_prefix {
6443 my ($line) = @_;
6444 my @chars = split //, $line;
6445 my $n = scalar @chars;
6446 my $i = 0;
6447 my @pairs = ();
6448  
6449 while (1) {
6450 # Skip leading spaces between successive assignments.
6451 $i++ while $i < $n && ($chars[$i] eq ' ' || $chars[$i] eq "\t");
6452 last if $i >= $n;
6453  
6454 # Match a variable name followed by '='.
6455 my $j = $i;
6456 my $name = '';
6457 if ($chars[$j] =~ /[A-Za-z_]/) {
6458 $name .= $chars[$j]; $j++;
6459 while ($j < $n && $chars[$j] =~ /[A-Za-z0-9_]/) { $name .= $chars[$j]; $j++ }
6460 }
6461 last unless length($name) && $j < $n && $chars[$j] eq '=';
6462 $j++; # consume '='
6463  
6464 # Read the value with quote / $() / backtick awareness.
6465 my $val = '';
6466 my $in_sq = 0;
6467 my $in_dq = 0;
6468 my $depth = 0; # $( ) nesting
6469 my $in_bt = 0; # backticks
6470 while ($j < $n) {
6471 my $c = $chars[$j];
6472 if ($in_sq) { $val .= $c; $in_sq = 0 if $c eq "'"; $j++; next }
6473 # Backslash escape (outside single quotes): the backslash and
6474 # the char it protects are both kept verbatim -- so "\ " does
6475 # not end the value word. _arr_dequote() resolves them later.
6476 if ($c eq "\\" && !$in_sq) {
6477 $val .= $c; $j++;
6478 $val .= $chars[$j] if $j < $n;
6479 $j++; next;
6480 }
6481 if ($c eq "'" && !$in_dq && !$in_bt) { $in_sq = 1; $val .= $c; $j++; next }
6482 if ($c eq '"' && !$in_bt) { $in_dq = !$in_dq; $val .= $c; $j++; next }
6483 if (!$in_dq && $c eq '`') { $in_bt = !$in_bt; $val .= $c; $j++; next }
6484 if (!$in_dq && !$in_bt && $c eq '$' && $j + 1 < $n && $chars[$j+1] eq '(') {
6485 $depth++; $val .= '$('; $j += 2; next;
6486 }
6487 if (!$in_dq && !$in_bt && $depth > 0 && $c eq ')') {
6488 $depth--; $val .= ')'; $j++; next;
6489 }
6490 if (!$in_sq && !$in_dq && !$in_bt && $depth == 0
6491 && ($c eq ' ' || $c eq "\t")) {
6492 last; # end of this value word
6493 }
6494 $val .= $c; $j++;
6495 }
6496  
6497 push @pairs, [$name, $val];
6498 $i = $j;
6499  
6500 # Peek: is there a following non-space token?
6501 my $k = $i;
6502 $k++ while $k < $n && ($chars[$k] eq ' ' || $chars[$k] eq "\t");
6503 last if $k >= $n; # nothing follows: trailing pure assignment(s)
6504  
6505 # Is the next token another assignment? If so, loop; otherwise the
6506 # remainder is the command.
6507 my $m = $k;
6508 my $nm2 = '';
6509 if ($chars[$m] =~ /[A-Za-z_]/) {
6510 $nm2 .= $chars[$m]; $m++;
6511 while ($m < $n && $chars[$m] =~ /[A-Za-z0-9_]/) { $nm2 .= $chars[$m]; $m++ }
6512 }
6513 if (length($nm2) && $m < $n && $chars[$m] eq '=') {
6514 $i = $k; # next assignment; continue the loop
6515 next;
6516 }
6517  
6518 # Remainder is a command.
6519 my $remainder = join('', @chars[$k .. $n-1]);
6520 return (\@pairs, $remainder);
6521 }
6522  
6523 # No command remainder: either not an assignment at all, or pure
6524 # assignment(s) which the normal post-expansion path handles.
6525 return () unless @pairs;
6526 return (\@pairs, '');
6527 }
6528  
6529 # ----------------------------------------------------------------
6530 # Here-document support (Perl 5.005_03 compatible)
6531 # ----------------------------------------------------------------
6532 # _hd_detect: scan a command line for an *unquoted* << operator.
6533 # Returns () if none found, otherwise:
6534 # ($cmd_part, $dash, $delim, $quoted)
6535 # where $cmd_part is the command with the "<< DELIM" token removed
6536 # (text after the delimiter, e.g. trailing redirections, is preserved),
6537 # $dash is 1 for <<- (strip leading tabs), $delim is the delimiter word,
6538 # and $quoted is 1 when the delimiter was quoted (suppresses expansion).
6539 sub _hd_detect {
6540 my ($line) = @_;
6541 my @chars = split //, $line;
6542 my $n = scalar @chars;
6543 my $in_sq = 0;
6544 my $in_dq = 0;
6545 my $arith = 0; # inside $(( ... )): << there is a shift, not a heredoc
6546 my $i = 0;
6547  
6548 while ($i < $n) {
6549 my $ch = $chars[$i];
6550  
6551 if ($in_sq) {
6552 $in_sq = 0 if $ch eq "'";
6553 $i++; next;
6554 }
6555 if ($ch eq "'" && !$in_dq) { $in_sq = 1; $i++; next }
6556 if ($ch eq '"' && !$in_sq) { $in_dq = !$in_dq; $i++; next }
6557 if ($ch eq '\\') { $i += 2; next }
6558  
6559 # Arithmetic expansion $(( ... )): skip its body entirely
6560 if ($ch eq '$' && $i+2 < $n && $chars[$i+1] eq '(' && $chars[$i+2] eq '(') {
6561 $arith++; $i += 3; next;
6562 }
6563 if ($arith && $ch eq ')' && $i+1 < $n && $chars[$i+1] eq ')') {
6564 $arith--; $i += 2; next;
6565 }
6566 if ($arith) { $i++; next }
6567  
6568 # Unquoted << starts a here-document; unquoted <<< is a
6569 # here-string (v0.07: handled later, after expansion, by
6570 # _sh_strip_herestring -- skip all three characters here so the
6571 # scan does not re-match starting at the second '<').
6572 if (!$in_dq && $ch eq '<' && $i+1 < $n && $chars[$i+1] eq '<'
6573 && $i+2 < $n && $chars[$i+2] eq '<') {
6574 $i += 3; next;
6575 }
6576 if (!$in_dq && $ch eq '<' && $i+1 < $n && $chars[$i+1] eq '<') {
6577 my $cmd_part = join('', @chars[0 .. $i-1]);
6578 my $j = $i + 2;
6579 my $dash = 0;
6580 if ($j < $n && $chars[$j] eq '-') { $dash = 1; $j++ }
6581 $j++ while $j < $n && ($chars[$j] eq ' ' || $chars[$j] eq "\t");
6582  
6583 my $quoted = 0;
6584 my $q = '';
6585 if ($j < $n && ($chars[$j] eq "'" || $chars[$j] eq '"')) {
6586 $quoted = 1; $q = $chars[$j]; $j++;
6587 }
6588 my $delim = '';
6589 if ($quoted) {
6590 while ($j < $n && $chars[$j] ne $q) { $delim .= $chars[$j]; $j++ }
6591 $j++ if $j < $n; # skip closing quote
6592 }
6593 else {
6594 while ($j < $n && $chars[$j] =~ /\w/) { $delim .= $chars[$j]; $j++ }
6595 }
6596 return () if $delim eq ''; # malformed; treat as ordinary line
6597  
6598 my $rest = join('', @chars[$j .. $n-1]);
6599 $cmd_part .= $rest; # preserve trailing tokens
6600 return ($cmd_part, $dash, $delim, $quoted);
6601 }
6602  
6603 $i++;
6604 }
6605 return ();
6606 }
6607  
6608 # _hd_tempfile: write $body to a uniquely-named temp file using
6609 # sysopen(... O_CREAT|O_EXCL ...) to avoid symlink races.
6610 # Returns the path, or undef on failure.
6611 sub _hd_tempfile {
6612 my ($body) = @_;
6613  
6614 my $dir = $ENV{'TMPDIR'} || $ENV{'TEMP'} || $ENV{'TMP'} || '';
6615 $dir = '/tmp' if $dir eq '' && -d '/tmp';
6616 $dir = '.' if $dir eq '';
6617 $dir =~ s{[\\/]+\z}{};
6618 $dir = '.' if !(-d $dir && -w $dir);
6619  
6620 my $attempt = 0;
6621 while ($attempt < 1000) {
6622 $_HD_SEQ++;
6623 $attempt++;
6624 my $path = $dir . '/' . 'batsh_hd_' . $$ . '_' . $_HD_SEQ;
6625 if (sysopen(_HD_TMP, $path, O_WRONLY | O_CREAT | O_EXCL, 0600)) {
6626 binmode(_HD_TMP);
6627 print _HD_TMP $body;
6628 close(_HD_TMP);
6629 push @_HD_TMPFILES, $path;
6630 return $path;
6631 }
6632 # EEXIST or transient error: retry with next sequence number
6633 }
6634 warn "sh: cannot create here-document temp file in $dir: $!\n";
6635 return undef;
6636 }
6637  
6638 # _hd_run: materialise the here-document body and run the command with
6639 # its STDIN connected to the body, reusing the existing redirect path.
6640 sub _hd_run {
6641 my ($class, $cmd_part, $body_ref, $quoted, $opts_ref) = @_;
6642  
6643 my @body = @{$body_ref};
6644 if (!$quoted) {
6645 for my $b (@body) { $b = _unprotect_lit(_expand($class, $b)) }
6646 }
6647 my $text = '';
6648 for my $b (@body) { $text .= BATsh::MB::dec($b) . "\n" }
6649  
6650 my $tmp = _hd_tempfile($text);
6651 if (!defined $tmp) { $LAST_STATUS = 2; return 2 }
6652  
6653 my @redir = ( [0, 0, $tmp] ); # fd=0 (stdin), append=0, source=tmp
6654 my $rc = _sh_exec_with_redirs($class, $cmd_part, \@redir, $opts_ref);
6655  
6656 unlink $tmp;
6657 @_HD_TMPFILES = grep { $_ ne $tmp } @_HD_TMPFILES;
6658 return $rc;
6659 }
6660  
6661 # Failsafe: remove any here-document temp files left behind on abnormal exit.
6662 END { for my $f (@_HD_TMPFILES) { unlink $f if defined $f } }
6663 END { for my $f (@_SUBST_TMPFILES) { unlink $f if defined $f } }
6664 END { for my $f (@_SHP_TMPFILES) { unlink $f if defined $f } }
6665 END { for my $f (@_PROCSUB_TMPFILES) { unlink $f if defined $f } }
6666  
6667 # Failsafe: remove any background-job pidfiles left behind on abnormal exit.
6668 END { for my $f (@_BG_TMPFILES) { unlink $f if defined $f } }
6669  
6670  
6671 # ----------------------------------------------------------------
6672 # Array / associative-array support (v0.06)
6673 # ----------------------------------------------------------------
6674 # Array names are case-insensitive, matching the scalar store: the key
6675 # stored in %_SH_ARRAY is always the uppercased name.
6676 sub _arr_name { return uc($_[0]) }
6677  
6678 sub _arr_exists {
6679 my ($name) = @_;
6680 return exists $_SH_ARRAY{ _arr_name($name) } ? 1 : 0;
6681 }
6682  
6683 sub _arr_is_assoc {
6684 my ($name) = @_;
6685 my $k = _arr_name($name);
6686 return (exists $_SH_ARRAY_TYPE{$k} && $_SH_ARRAY_TYPE{$k} eq 'assoc') ? 1 : 0;
6687 }
6688  
6689 # Evaluate an indexed-array subscript as an integer. Plain integers are
6690 # taken verbatim; anything else is run through the arithmetic evaluator so
6691 # that subscripts such as "1+1" or a bare variable name work like bash.
6692 sub _arr_index {
6693 my ($s) = @_;
6694 $s = '' unless defined $s;
6695 $s =~ s/\A\s+//; $s =~ s/\s+\z//;
6696 return 0 if $s eq '';
6697 return int($s) if $s =~ /\A-?\d+\z/;
6698 my $v = _eval_arith($s);
6699 return ($v =~ /\A-?\d+\z/) ? int($v) : 0;
6700 }
6701  
6702 # Resolve $VAR / ${VAR} inside a subscript (no command substitution, no
6703 # arithmetic -- those are applied later for indexed subscripts).
6704 sub _arr_expand_sub {
6705 my ($class, $s) = @_;
6706 return '' unless defined $s;
6707 $s =~ s/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/
6708 do { my $v = BATsh::Env->get($1); defined $v ? $v : '' }
6709 /ge;
6710 $s =~ s/\$([A-Za-z_][A-Za-z0-9_]*)/
6711 do { my $v = BATsh::Env->get($1); defined $v ? $v : '' }
6712 /ge;
6713 return $s;
6714 }
6715  
6716 # Element keys in display order: ascending numeric (indexed) or sorted
6717 # string (assoc).
6718 sub _arr_ordered_keys {
6719 my ($name) = @_;
6720 my $k = _arr_name($name);
6721 return () unless exists $_SH_ARRAY{$k};
6722 my $h = $_SH_ARRAY{$k};
6723 if ((defined $_SH_ARRAY_TYPE{$k} && $_SH_ARRAY_TYPE{$k} eq 'assoc')) {
6724 return sort keys %{$h};
6725 }
6726 return sort { $a <=> $b } keys %{$h};
6727 }
6728  
6729 sub _arr_values {
6730 my ($name) = @_;
6731 my $k = _arr_name($name);
6732 return () unless exists $_SH_ARRAY{$k};
6733 my $h = $_SH_ARRAY{$k};
6734 return map { $h->{$_} } _arr_ordered_keys($name);
6735 }
6736  
6737 sub _arr_count {
6738 my ($name) = @_;
6739 my $k = _arr_name($name);
6740 return 0 unless exists $_SH_ARRAY{$k};
6741 return scalar keys %{$_SH_ARRAY{$k}};
6742 }
6743  
6744 # Fetch a single element. $sub is already $VAR-expanded by the caller.
6745 # Returns undef when the element is unset.
6746 sub _arr_get_element {
6747 my ($name, $sub) = @_;
6748 my $k = _arr_name($name);
6749 return undef unless exists $_SH_ARRAY{$k};
6750 my $h = $_SH_ARRAY{$k};
6751 if ((defined $_SH_ARRAY_TYPE{$k} && $_SH_ARRAY_TYPE{$k} eq 'assoc')) {
6752 return exists $h->{$sub} ? $h->{$sub} : undef;
6753 }
6754 my $idx = _arr_index($sub);
6755 if ($idx < 0) {
6756 # Negative subscript: count back over the ordered set of set indices.
6757 my @keys = _arr_ordered_keys($name);
6758 return undef unless @keys;
6759 my $kk = $keys[$idx];
6760 return defined $kk ? $h->{$kk} : undef;
6761 }
6762 return exists $h->{$idx} ? $h->{$idx} : undef;
6763 }
6764  
6765 # Remove shell quoting from a value: drop unescaped quote characters while
6766 # honouring single- vs double-quote regions. Handles whole-token quotes
6767 # ("a b") and partial quotes (foo"a b"bar) alike.
6768 sub _arr_dequote {
6769 my ($v) = @_;
6770 return '' unless defined $v;
6771 my $out = '';
6772 my $in_sq = 0;
6773 my $in_dq = 0;
6774 my @c = split //, $v;
6775 my $n = scalar @c;
6776 my $i = 0;
6777 while ($i < $n) {
6778 my $c = $c[$i];
6779 # Single quotes: everything literal, no escapes, until the closer.
6780 if ($in_sq) {
6781 if ($c eq "'") { $in_sq = 0 } else { $out .= $c }
6782 $i++; next;
6783 }
6784 if ($c eq "'" && !$in_dq) { $in_sq = 1; $i++; next }
6785 # Backslash: escape processing (POSIX).
6786 if ($c eq '\\') {
6787 my $nx = ($i+1 < $n) ? $c[$i+1] : '';
6788 if ($in_dq) {
6789 # Inside "..." backslash is literal EXCEPT before $ ` " \.
6790 if ($nx eq '"' || $nx eq '\\' || $nx eq '`' || $nx eq '$') {
6791 $out .= $nx; $i += 2; next;
6792 }
6793 $out .= '\\'; $i++; next;
6794 }
6795 # Unquoted: backslash quotes the following char (so \" is a
6796 # literal quote and does NOT open a quoted region).
6797 if ($nx ne '') { $out .= $nx; $i += 2; next }
6798 $out .= '\\'; $i++; next;
6799 }
6800 if ($c eq '"' && !$in_sq) { $in_dq = !$in_dq; $i++; next }
6801 $out .= $c; $i++;
6802 }
6803 # A backslash that came out of an expansion is literal data, never a
6804 # shell escape: restore it now that quote removal has finished.
6805 return _unprotect_lit($out);
6806 }
6807  
6808 # Split a string on unquoted whitespace, KEEPING the quote characters in
6809 # each returned token (so the caller can tell whether a token was quoted).
6810 sub _arr_split_words {
6811 my ($s) = @_;
6812 $s = '' unless defined $s;
6813 my @words;
6814 my $cur = '';
6815 my $have = 0;
6816 my $in_sq = 0;
6817 my $in_dq = 0;
6818 my $in_bt = 0; # backtick `...`
6819 my $pdep = 0; # $( ... and <( >( and plain ( ) depth
6820 my $bdep = 0; # ${ ... } depth
6821 my @chars = split //, $s;
6822 my $n = scalar @chars;
6823 my $i = 0;
6824 while ($i < $n) {
6825 my $c = $chars[$i];
6826 if ($in_sq) { $cur .= $c; $in_sq = 0 if $c eq "'"; $have = 1; $i++; next }
6827 if ($c eq "'" && !$in_dq && !$in_bt) { $in_sq = 1; $cur .= $c; $have = 1; $i++; next }
6828 if ($c eq '"' && !$in_bt) { $in_dq = !$in_dq; $cur .= $c; $have = 1; $i++; next }
6829 # Backslash escape keeps the next char attached to this word.
6830 if ($c eq '\\') { $cur .= $c; $have = 1; $i++; $cur .= $chars[$i] if $i < $n; $i++; next }
6831 if ($c eq '`') { $in_bt = !$in_bt; $cur .= $c; $have = 1; $i++; next }
6832 # Command / parameter substitution regions are opaque so their
6833 # internal whitespace does not word-split (e.g. $(echo a b c)).
6834 if (!$in_dq) {
6835 if ($c eq '$' && $i+1 < $n && $chars[$i+1] eq '{') { $bdep++; $cur .= '${'; $have = 1; $i += 2; next }
6836 if ($bdep > 0 && $c eq '}') { $bdep--; $cur .= $c; $have = 1; $i++; next }
6837 if ($c eq '(') { $pdep++; $cur .= $c; $have = 1; $i++; next }
6838 if ($c eq ')' && $pdep > 0) { $pdep--; $cur .= $c; $have = 1; $i++; next }
6839 }
6840 if (!$in_sq && !$in_dq && !$in_bt && $pdep == 0 && $bdep == 0 && $c =~ /\s/) {
6841 if ($have) { push @words, $cur; $cur = ''; $have = 0 }
6842 $i++; next;
6843 }
6844 $cur .= $c; $have = 1; $i++;
6845 }
6846 push @words, $cur if $have;
6847 return @words;
6848 }
6849  
6850 # Parse the body of a (...) array literal into a list of [subscript, value]
6851 # pairs. $subscript is undef for positional elements and a string for
6852 # explicit [sub]=value elements.
6853 sub _arr_parse_elements {
6854 my ($class, $body) = @_;
6855 my @raw = _arr_split_words($body);
6856 my @out;
6857 for my $tok (@raw) {
6858 my ($sub, $vpart);
6859 if ($tok =~ /\A\[(.*?)\]=(.*)\z/s) {
6860 ($sub, $vpart) = ($1, $2);
6861 }
6862 else {
6863 ($sub, $vpart) = (undef, $tok);
6864 }
6865 my $raw_has_quote = ($vpart =~ /['"]/) ? 1 : 0;
6866 my $exp = _expand($class, $vpart);
6867 if (defined $sub) {
6868 $sub = _arr_dequote(_expand($class, $sub));
6869 push @out, [$sub, _arr_dequote($exp)];
6870 }
6871 elsif (!$raw_has_quote && $exp =~ /\s/) {
6872 # Unquoted expansion is subject to word splitting.
6873 for my $w (split /\s+/, $exp) {
6874 next if $w eq '';
6875 push @out, [undef, $w];
6876 }
6877 }
6878 else {
6879 push @out, [undef, _arr_dequote($exp)];
6880 }
6881 }
6882 return @out;
6883 }
6884  
6885 # arr=( ... ) / arr+=( ... ) whole-array assignment or append.
6886 sub _arr_assign_literal {
6887 my ($class, $name, $body, $append) = @_;
6888 my $k = _arr_name($name);
6889 my $assoc = _arr_is_assoc($name); # honour a prior 'declare -A'
6890  
6891 if (!$append) {
6892 $_SH_ARRAY{$k} = {};
6893 $_SH_ARRAY_TYPE{$k} = $assoc ? 'assoc' : 'indexed';
6894 }
6895 else {
6896 $_SH_ARRAY{$k} = {} unless exists $_SH_ARRAY{$k};
6897 $_SH_ARRAY_TYPE{$k} = ($assoc ? 'assoc' : 'indexed')
6898 unless exists $_SH_ARRAY_TYPE{$k};
6899 }
6900 BATsh::Env->unset($name); # a name is array OR scalar, not both
6901  
6902 my $is_assoc = ($_SH_ARRAY_TYPE{$k} eq 'assoc');
6903 my @elems = _arr_parse_elements($class, $body);
6904  
6905 if ($is_assoc) {
6906 for my $e (@elems) {
6907 my ($sub, $val) = @{$e};
6908 $sub = '' unless defined $sub;
6909 $_SH_ARRAY{$k}{$sub} = $val;
6910 }
6911 }
6912 else {
6913 my $next = 0;
6914 for my $ix (keys %{$_SH_ARRAY{$k}}) {
6915 $next = $ix + 1 if $ix =~ /\A-?\d+\z/ && $ix + 1 > $next;
6916 }
6917 for my $e (@elems) {
6918 my ($sub, $val) = @{$e};
6919 if (defined $sub && $sub ne '') {
6920 my $ix = _arr_index($sub);
6921 $_SH_ARRAY{$k}{$ix} = $val;
6922 $next = $ix + 1;
6923 }
6924 else {
6925 $_SH_ARRAY{$k}{$next} = $val;
6926 $next++;
6927 }
6928 }
6929 }
6930 $LAST_STATUS = 0;
6931 return 0;
6932 }
6933  
6934 # arr[sub]=value / arr[sub]+=value single-element assignment or append.
6935 sub _arr_assign_element {
6936 my ($class, $name, $sub, $rawval, $append) = @_;
6937 my $val = _expand($class, $rawval);
6938 $val =~ s/\A"(.*)"\z/$1/s;
6939 $val =~ s/\A'(.*)'\z/$1/s;
6940 my $k = _arr_name($name);
6941 $sub = _arr_expand_sub($class, $sub);
6942 if (!exists $_SH_ARRAY{$k}) {
6943 $_SH_ARRAY{$k} = {};
6944 $_SH_ARRAY_TYPE{$k} = 'indexed';
6945 }
6946 BATsh::Env->unset($name);
6947 my $key = (defined $_SH_ARRAY_TYPE{$k} && $_SH_ARRAY_TYPE{$k} eq 'assoc')
6948 ? $sub : _arr_index($sub);
6949 if ($append) {
6950 my $old = exists $_SH_ARRAY{$k}{$key} ? $_SH_ARRAY{$k}{$key} : '';
6951 $_SH_ARRAY{$k}{$key} = $old . $val;
6952 }
6953 else {
6954 $_SH_ARRAY{$k}{$key} = $val;
6955 }
6956 $LAST_STATUS = 0;
6957 return 0;
6958 }
6959  
6960 # declare / typeset [-aA] NAME[=(...)] ... array (and scalar) declaration.
6961 sub _cmd_declare {
6962 my ($class, $rest) = @_;
6963 $rest = '' unless defined $rest;
6964 $rest =~ s/\A\s+//;
6965  
6966 my $type; # 'assoc' | 'indexed' | undef
6967 my $intattr = 0;
6968 my $roattr = 0;
6969 while ($rest =~ s/\A(-[A-Za-z]+)\s+//) {
6970 my $flag = $1;
6971 if ($flag =~ /A/) { $type = 'assoc' }
6972 elsif ($flag =~ /a/) { $type = 'indexed' unless defined $type }
6973 $intattr = 1 if $flag =~ /i/;
6974 $roattr = 1 if $flag =~ /r/;
6975 }
6976  
6977 while ($rest ne '') {
6978 $rest =~ s/\A\s+//;
6979 last if $rest eq '';
6980 if ($rest =~ /\A([A-Za-z_][A-Za-z0-9_]*)\+?=\((.*)\)\s*(.*)\z/s) {
6981 my ($name, $body, $tail) = ($1, $2, $3);
6982 my $k = _arr_name($name);
6983 $_SH_ARRAY_TYPE{$k} = $type if defined $type;
6984 _arr_assign_literal($class, $name, $body, 0);
6985 $rest = $tail;
6986 }
6987 elsif ($rest =~ /\A([A-Za-z_][A-Za-z0-9_]*)=((?:"[^"]*"|'[^']*'|\S)*)\s*(.*)\z/s) {
6988 my ($name, $val, $tail) = ($1, $2, $3);
6989 if (defined $type) {
6990 # Typed array declared with a scalar initialiser: seed [0].
6991 my $k = _arr_name($name);
6992 $_SH_ARRAY_TYPE{$k} = $type;
6993 _arr_assign_element($class, $name, '0', $val, 0);
6994 }
6995 else {
6996 $val = _expand($class, $val);
6997 $val =~ s/\A"(.*)"\z/$1/s;
6998 $val =~ s/\A'(.*)'\z/$1/s;
6999 my $ik = uc($name);
7000 $_SH_INTATTR{$ik} = 1 if $intattr;
7001 # "declare -i x=EXPR" evaluates the right hand side as
7002 # arithmetic; _sh_store_scalar re-applies this for any
7003 # later plain "x=..." assignment because the attribute
7004 # sticks in %_SH_INTATTR.
7005 $val = _eval_arith($val) if $_SH_INTATTR{$ik};
7006 if (_sh_is_readonly($name)) {
7007 print STDERR "sh: $name: readonly variable\n";
7008 $LAST_STATUS = 1;
7009 }
7010 else {
7011 BATsh::Env->set($name, $val);
7012 }
7013 $_SH_READONLY{$ik} = 1 if $roattr;
7014 }
7015 $rest = $tail;
7016 }
7017 elsif ($rest =~ /\A([A-Za-z_][A-Za-z0-9_]*)\s*(.*)\z/s) {
7018 my ($name, $tail) = ($1, $2);
7019 if (($intattr || $roattr) && !defined $type) {
7020 # Attribute-only declaration: mark the variable, do NOT
7021 # turn it into an (empty) array.
7022 my $ik = uc($name);
7023 $_SH_INTATTR{$ik} = 1 if $intattr;
7024 $_SH_READONLY{$ik} = 1 if $roattr;
7025 }
7026 else {
7027 my $k = _arr_name($name);
7028 $_SH_ARRAY{$k} = {} unless exists $_SH_ARRAY{$k};
7029 $_SH_ARRAY_TYPE{$k} = (defined $type ? $type : 'indexed');
7030 }
7031 $rest = $tail;
7032 }
7033 else {
7034 last;
7035 }
7036 }
7037 $LAST_STATUS = 0 unless $LAST_STATUS;
7038 return $LAST_STATUS;
7039 }
7040  
7041 # _sh_try_array_op: detect and perform an array operation on the RAW line.
7042 # Returns (1, $status) when it handled the line, or () otherwise.
7043 sub _sh_try_array_op {
7044 my ($class, $line, $opts_ref) = @_;
7045 my $s = $line;
7046 $s =~ s/\A\s+//; $s =~ s/\s+\z//;
7047 $s =~ s/\s*;\s*\z//; # tolerate one trailing ';'
7048  
7049 # declare / typeset / local with array semantics
7050 if ($s =~ /\A(declare|typeset|local)\b\s*(.*)\z/is) {
7051 my ($kw, $args) = ($1, $2);
7052 my $is_local = (lc($kw) eq 'local');
7053 my $has_arr_flag = ($args =~ /\A-[A-Za-z]*[aA]/) ? 1 : 0;
7054 my $has_arr_init = ($args =~ /=\(/) ? 1 : 0;
7055 if (!$is_local || $has_arr_flag || $has_arr_init) {
7056 return (1, _cmd_declare($class, $args));
7057 }
7058 return (); # plain 'local x=1' -> handled by _cmd_local
7059 }
7060  
7061 # NAME=( ... ) or NAME+=( ... ) -- whole-line array literal
7062 if ($s =~ /\A([A-Za-z_][A-Za-z0-9_]*)(\+?)=\((.*)\)\z/s) {
7063 my ($name, $plus, $body) = ($1, $2, $3);
7064 return (1, _arr_assign_literal($class, $name, $body,
7065 ($plus eq '+') ? 1 : 0));
7066 }
7067  
7068 # NAME[SUB]=VALUE or NAME[SUB]+=VALUE -- single-element assignment
7069 if ($s =~ /\A([A-Za-z_][A-Za-z0-9_]*)\[([^\]]*)\](\+?)=(.*)\z/s) {
7070 my ($name, $sub, $plus, $val) = ($1, $2, $3, $4);
7071 return (1, _arr_assign_element($class, $name, $sub, $val,
7072 ($plus eq '+') ? 1 : 0));
7073 }
7074  
7075 return ();
7076 }
7077  
7078 # _expand_word_list: turn a for-loop list string into a list of items.
7079 # Resolves variables / command substitution, applies filename globbing to
7080 # unquoted glob words, and expands a whole-word ${arr[@]} / ${arr[*]}
7081 # reference (quoted or not) to one item per array element.
7082 sub _expand_word_list {
7083 my ($class, $list_str) = @_;
7084 $list_str = _brace_expand_line($list_str) if defined $list_str && $list_str =~ /\{/;
7085 my @raw = _arr_split_words($list_str);
7086 my @items;
7087 for my $tok (@raw) {
7088 # Whole-word ${arr[@]} / ${arr[*]} -> one item per element value.
7089 if ($tok =~ /\A"?\$\{([A-Za-z_][A-Za-z0-9_]*)\[[\@*]\]\}"?\z/
7090 && _arr_exists($1)) {
7091 push @items, _arr_values($1);
7092 next;
7093 }
7094 # Whole-word ${!arr[@]} / ${!arr[*]} -> one item per index / key.
7095 if ($tok =~ /\A"?\$\{!([A-Za-z_][A-Za-z0-9_]*)\[[\@*]\]\}"?\z/
7096 && _arr_exists($1)) {
7097 push @items, _arr_ordered_keys($1);
7098 next;
7099 }
7100 my $raw_has_quote = ($tok =~ /['"]/) ? 1 : 0;
7101 my $exp = _arr_dequote(_expand($class, $tok));
7102 if (!$raw_has_quote) {
7103 if ($exp =~ /[*?\[]/) {
7104 push @items, _glob_expand($exp);
7105 }
7106 elsif ($exp =~ /\s/) {
7107 push @items, grep { $_ ne '' } split /\s+/, $exp;
7108 }
7109 elsif ($exp ne '') {
7110 push @items, $exp;
7111 }
7112 # an empty unquoted word expands to nothing
7113 }
7114 else {
7115 push @items, $exp;
7116 }
7117 }
7118 return @items;
7119 }
7120  
7121 # ----------------------------------------------------------------
7122 # Accessors
7123 # ----------------------------------------------------------------
7124 sub last_status { return $LAST_STATUS }
7125 sub set_last_status { $LAST_STATUS = $_[1] }
7126  
7127 # Need Cwd
7128 BEGIN {
7129 eval { require Cwd };
7130 if ($@) {
7131 eval 'sub Cwd::cwd { return $ENV{PWD} || "." }';
7132 }
7133 }
7134  
7135 1;
7136  
7137 __END__