Debian Codegraph @

interp/interp_test.go

raw
1 // Copyright (c) 2017, Daniel Martí <[email protected]>
2 // See LICENSE for licensing information
3
4 package interp_test
5
6 import (
7 "bytes"
8 "context"
9 "errors"
10 "fmt"
11 "io"
12 "math/bits"
13 "os"
14 "os/exec"
15 "path/filepath"
16 "regexp"
17 "runtime"
18 "slices"
19 "strings"
20 "sync"
21 "testing"
22 "time"
23
24 "github.com/go-quicktest/qt"
25 "mvdan.cc/sh/v3/expand"
26 "mvdan.cc/sh/v3/internal"
27 "mvdan.cc/sh/v3/interp"
28 "mvdan.cc/sh/v3/syntax"
29 )
30
31 // runnerRunTimeout is the context timeout used by any tests calling [Runner.Run].
32 // The timeout saves us from hangs or burning too much CPU if there are bugs.
33 // All the test cases are designed to be inexpensive and stop in a very short
34 // amount of time, so 5s should be plenty even for busy machines.
35 const runnerRunTimeout = 5 * time.Second
36
37 // Some program which should be in $PATH. Needs to run before runTests is
38 // initialized (so an init function wouldn't work), because runTest uses it.
39 var pathProg = func() string {
40 if runtime.GOOS == "windows" {
41 return "cmd"
42 }
43 return "sh"
44 }()
45
46 func parse(tb testing.TB, parser *syntax.Parser, src string) *syntax.File {
47 if parser == nil {
48 parser = syntax.NewParser()
49 }
50 file, err := parser.Parse(strings.NewReader(src), "")
51 if err != nil {
52 tb.Fatal(err)
53 }
54 return file
55 }
56
57 func BenchmarkRun(b *testing.B) {
58 b.ReportAllocs()
59
60 src := `
61 echo a b c d
62 echo ./$foo/etc $(echo foo bar)
63 foo="bar"
64 x=y :
65 fn() {
66 local a=b
67 for i in 1 2 3; do
68 echo $i | cat
69 done
70 }
71 [[ $foo == bar ]] && fn
72 echo a{b,c}d *.go
73 let i=(2 + 3)
74 `
75 file := parse(b, nil, src)
76 r, _ := interp.New()
77 ctx := b.Context()
78
79 for b.Loop() {
80 r.Reset()
81 if err := r.Run(ctx, file); err != nil {
82 b.Fatal(err)
83 }
84 }
85 }
86
87 var hasBash53 bool
88
89 func TestMain(m *testing.M) {
90 if os.Getenv("GOSH_PROG") != "" {
91 switch os.Getenv("GOSH_CMD") {
92 case "exit_0":
93 os.Exit(0)
94 case "exit_5":
95 os.Exit(5)
96 case "print_ok":
97 fmt.Printf("exec ok\n")
98 os.Exit(0)
99 case "print_fail":
100 fmt.Printf("exec fail\n")
101 os.Exit(1)
102 case "pid_and_hang":
103 fmt.Println(os.Getpid())
104 time.Sleep(time.Hour)
105 os.Exit(0)
106 case "foo_null_bar":
107 fmt.Println("foo\x00bar")
108 os.Exit(0)
109 case "lookpath":
110 _, err := exec.LookPath(pathProg)
111 if err != nil {
112 fmt.Println(err)
113 os.Exit(1)
114 }
115 fmt.Printf("%s found\n", pathProg)
116 os.Exit(0)
117 }
118 r := strings.NewReader(os.Args[1])
119 file, err := syntax.NewParser().Parse(r, "")
120 if err != nil {
121 fmt.Fprintln(os.Stderr, err)
122 os.Exit(1)
123 }
124 runner, _ := interp.New(
125 interp.StdIO(os.Stdin, os.Stdout, os.Stderr),
126 interp.ExecHandlers(testExecHandler),
127 )
128 ctx := context.Background()
129 if err := runner.Run(ctx, file); err != nil {
130 if es, ok := errors.AsType[interp.ExitStatus](err); ok {
131 os.Exit(int(es))
132 }
133
134 fmt.Fprintln(os.Stderr, err)
135 os.Exit(1)
136 }
137 os.Exit(0)
138 }
139
140 if canExec {
141 prog, err := os.Executable()
142 if err != nil {
143 panic(err)
144 }
145 os.Setenv("GOSH_PROG", prog)
146 }
147
148 internal.TestMainSetup()
149
150 hasBash53 = checkBash()
151
152 wd, err := os.Getwd()
153 if err != nil {
154 panic(err)
155 }
156 os.Setenv("GO_TEST_DIR", wd)
157
158 os.Setenv("INTERP_GLOBAL", "value")
159 os.Setenv("MULTILINE_INTERP_GLOBAL", "\nwith\nnewlines\n\n")
160
161 // Double check that env vars on Windows are case insensitive.
162 if runtime.GOOS == "windows" {
163 os.Setenv("mixedCase_INTERP_GLOBAL", "value")
164 } else {
165 os.Setenv("MIXEDCASE_INTERP_GLOBAL", "value")
166 }
167
168 os.Setenv("PATH_PROG", pathProg)
169
170 // To print env vars. Only a builtin on Windows.
171 if runtime.GOOS == "windows" {
172 os.Setenv("ENV_PROG", "cmd /c set")
173 } else {
174 os.Setenv("ENV_PROG", "env")
175 }
176
177 m.Run()
178 }
179
180 func checkBash() bool {
181 out, err := exec.Command("bash", "-c", "echo -n $BASH_VERSION").Output()
182 if err != nil {
183 return false
184 }
185 return strings.HasPrefix(string(out), "5.3")
186 }
187
188 // concBuffer wraps a [bytes.Buffer] in a mutex so that concurrent writes
189 // to it don't upset the race detector.
190 type concBuffer struct {
191 buf bytes.Buffer
192 sync.Mutex
193 }
194
195 func (c *concBuffer) Write(p []byte) (int, error) {
196 c.Lock()
197 n, err := c.buf.Write(p)
198 c.Unlock()
199 return n, err
200 }
201
202 func (c *concBuffer) WriteString(s string) (int, error) {
203 c.Lock()
204 n, err := c.buf.WriteString(s)
205 c.Unlock()
206 return n, err
207 }
208
209 func (c *concBuffer) String() string {
210 c.Lock()
211 s := c.buf.String()
212 c.Unlock()
213 return s
214 }
215
216 func (c *concBuffer) Reset() {
217 c.Lock()
218 c.buf.Reset()
219 c.Unlock()
220 }
221
222 type runTest struct {
223 in, want string
224 }
225
226 var runTests = []runTest{
227 // no-op programs
228 {"", ""},
229 {"true", ""},
230 {":", ""},
231 {"exit", ""},
232 {"exit 0", ""},
233 {"{ :; }", ""},
234 {"(:)", ""},
235
236 // help
237 {"help -s pwd", "pwd: pwd [-LP]\n"},
238 {"help -d true", "true - Return a successful result.\n"},
239 {"help -s ec*", "echo: echo [-neE] [arg ...]\n #IGNORE bash prints a `Shell commands matching keyword' header"},
240 {"help nosuchthing", "help: no help topics match `nosuchthing'. Try `help help'.\nexit status 1 #IGNORE bash also suggests man and info"},
241 {"help -q", "help: -q: invalid option\nhelp: usage: help [-dms] [pattern ...]\nexit status 2 #IGNORE bash prefixes its errors with `bash: line N:'"},
242 // a builtin we recognize but do not implement is starred, so that help is
243 // an honest statement of what this shell can do
244 {"help -s jobs", "jobs: jobs [-lnprs] [jobspec ...]\n #IGNORE bash implements jobs, and its synopsis differs"},
245 {"help jobs", "jobs: jobs [-lnprs] [jobspec ...]\n Display status of jobs.\n (recognized by this shell but not implemented)\n\n #IGNORE bash implements jobs"},
246
247 // times
248 {"times", "0m0.000s 0m0.000s\n0m0.000s 0m0.000s\n #IGNORE we report zeros; bash reports real CPU time"},
249
250 // exit status codes
251 {"exit 1", "exit status 1"},
252 {"exit -1", "exit status 255"},
253 {"exit 300", "exit status 44"},
254 {"false", "exit status 1"},
255 {"false foo", "exit status 1"},
256 {"! false", ""},
257 {"true foo", ""},
258 {": foo", ""},
259 {"! true", "exit status 1"},
260 {"false; true", ""},
261 {"false; exit", "exit status 1"},
262 {"exit; echo foo", ""},
263 {"exit 0; echo foo", ""},
264 {"printf", "usage: printf format [arguments]\nexit status 2 #JUSTERR"},
265 {"break", "break is only useful in a loop\n #JUSTERR"},
266 {"continue", "continue is only useful in a loop\n #JUSTERR"},
267 {"cd a b", "usage: cd [dir]\nexit status 2 #JUSTERR"},
268 {"shift a", "usage: shift [n]\nexit status 2 #JUSTERR"},
269 {
270 "shouldnotexist",
271 "\"shouldnotexist\": executable file not found in $PATH\nexit status 127 #JUSTERR",
272 },
273 {
274 "for i in 1; do continue a; done",
275 "usage: continue [n]\nexit status 2 #JUSTERR",
276 },
277 {
278 "for i in 1; do break a; done",
279 "usage: break [n]\nexit status 2 #JUSTERR",
280 },
281 {"false; a=b", ""},
282 {"false; false &", ""},
283 {
284 "GOSH_CMD=exit_0 $GOSH_PROG; echo next",
285 "next\n",
286 },
287 {
288 "GOSH_CMD=exit_5 $GOSH_PROG; echo next",
289 "next\n",
290 },
291 {
292 "! GOSH_CMD=exit_0 $GOSH_PROG",
293 "exit status 1",
294 },
295 {
296 "! GOSH_CMD=exit_5 $GOSH_PROG",
297 "",
298 },
299
300 // we don't need to follow bash error strings
301 {"exit a", "invalid exit status code: \"a\"\nexit status 2 #JUSTERR"},
302 {"exit 1 2", "exit cannot take multiple arguments\nexit status 1 #JUSTERR"},
303 {"f() { return a; }; f", "invalid return status code: \"a\"\nexit status 2 #JUSTERR"},
304
305 // echo
306 {"echo", "\n"},
307 {"echo a b c", "a b c\n"},
308 {"echo -n foo", "foo"},
309 {`echo -e '\t'`, "\t\n"},
310 {`echo -E '\t'`, "\\t\n"},
311 {`echo -e 'before\x00after'`, "before\x00after\n"},
312 {"echo -x foo", "-x foo\n"},
313 {"echo -e -x -e foo", "-x -e foo\n"},
314
315 // printf
316 {"printf foo", "foo"},
317 {"printf %%", "%"},
318 {"printf %", "missing format char\nexit status 1 #JUSTERR"},
319 {"printf %; echo foo", "missing format char\nfoo\n #IGNORE"},
320 {"printf %1", "missing format char\nexit status 1 #JUSTERR"},
321 {"printf %+", "missing format char\nexit status 1 #JUSTERR"},
322 {"printf %B foo", "invalid format char: B\nexit status 1 #JUSTERR"},
323 {"printf %12-s foo", "invalid format char: -\nexit status 1 #JUSTERR"},
324 {"printf ' %s \n' bar", " bar \n"},
325 {"printf '\\A'", "\\A"},
326 {"printf %s foo", "foo"},
327 {"printf %s", ""},
328 {"printf %d,%i 3 4", "3,4"},
329 {"printf %d", "0"},
330 {"printf %d,%d 010 0x10", "8,16"},
331 {"printf %c,%c,%c foo àa", "f,\xc3,\x00"}, // TODO: use a rune?
332 {"printf %3s a", " a"},
333 {"printf %3i 1", " 1"},
334 {"printf %+i%+d 1 -3", "+1-3"},
335 {"printf %-5x 10", "a "},
336 {"printf %02x 1", "01"},
337 {"printf 'a% 5s' a", "a a"},
338 {"printf 'nofmt' 1 2 3", "nofmt"},
339 {"printf '%d_' 1 2 3", "1_2_3_"},
340 {"printf '%02d %02d\n' 1 2 3", "01 02\n03 00\n"},
341 {`printf '0%s1' 'a\bc'`, `0a\bc1`},
342 {`printf '0%b1' 'a\bc'`, "0a\bc1"},
343 {"printf 'a%bc'", "ac"},
344 {"printf 'before\\x00after'", "before\x00after"},
345
346 // printf escape sequences at end of format string (must not panic)
347 {"printf '\\0'", "\x00"},
348 {"printf '\\01'", "\x01"},
349 {"printf '\\x'", "\\x #IGNORE bash prints a warning to stderr"},
350 {"printf 'a\\0'", "a\x00"},
351 {"printf '\\\\'", "\\"},
352
353 // words and quotes
354 {"echo foo ", "foo\n"},
355 {"echo ' foo '", " foo \n"},
356 {`echo " foo "`, " foo \n"},
357 {`echo a'b'c"d"e`, "abcde\n"},
358 {`a=" b c "; echo $a`, "b c\n"},
359 {`a=" b c "; echo "$a"`, " b c \n"},
360 {`a=" b c "; echo foo${a}bar`, "foo b c bar\n"},
361 {`a="b c"; echo foo${a}bar`, "foob cbar\n"},
362 {`echo "$(echo ' b c ')"`, " b c \n"},
363 {"echo \"`echo \\\"foobar\\\"`\"", "foobar\n"},
364 {"echo ''", "\n"},
365 {`$(echo)`, ""},
366 {`echo -n '\\'`, `\\`},
367 {`echo -n "\\"`, `\`},
368 {`set -- a b c; x="$@"; echo "$x"`, "a b c\n"},
369 {`set -- b c; echo a"$@"d`, "ab cd\n"},
370 {`count() { echo $#; }; set --; count "$@"`, "0\n"},
371 {`count() { echo $#; }; set -- ""; count "$@"`, "1\n"},
372 {`count() { echo $#; }; set -- ""; shift; count "$@"`, "0\n"},
373 {`count() { echo $#; }; a=(); count "${a[@]}"`, "0\n"},
374 {`count() { echo $#; }; count "${unset_var[@]}"`, "0\n"},
375 {`count() { echo $#; }; a=(""); count "${a[@]}"`, "1\n"},
376 {`echo $1 $3; set -- a b c; echo $1 $3`, "\na c\n"},
377 {`[[ $0 == "bash" || $0 == "gosh" ]]`, ""},
378
379 // dollar quotes
380 {`echo $'foo\nbar'`, "foo\nbar\n"},
381 {`echo $'\r\t\\'`, "\r\t\\\n"},
382 {`echo $"foo\nbar"`, "foo\\nbar\n"},
383 {`echo $'%s'`, "%s\n"},
384 {`a=$'\r\t\\'; echo "$a"`, "\r\t\\\n"},
385 {`a=$"foo\nbar"; echo "$a"`, "foo\\nbar\n"},
386 {`echo $'\a\b\e\E\f\v'`, "\a\b\x1b\x1b\f\v\n"},
387 {`echo $'\\\'\"\?'`, "\\'\"?\n"},
388 {`echo $'\1\45\12345\777\9'`, "\x01%S45\xff\\9\n"},
389 {`echo $'\x\xf\x09\xAB'`, "\\x\x0f\x09\xab\n"},
390 {`echo $'\u\uf\u09\uABCD\u00051234'`, "\\u\u000f\u0009\uabcd\u00051234\n"},
391 {`echo $'\U\Uf\U09\UABCD\U00051234'`, "\\U\u000f\u0009\uabcd\U00051234\n"},
392 {
393 "echo 'before\x00after'",
394 "beforeafter\n",
395 },
396 {
397 "echo \"before\x00after\"",
398 "beforeafter\n",
399 },
400 {
401 "echo $'before\x00after'",
402 "beforeafter\n",
403 },
404 {
405 "echo $'before\\x00after'",
406 "before\n",
407 },
408 {
409 "echo $'before\\xafter'",
410 "before\xafter\n",
411 },
412 {
413 "a='before\x00after'; eval \"echo -n ${a} ${a@Q}\";",
414 "beforeafter beforeafter",
415 },
416 {
417 "a=$'before\\x00after'; eval \"echo -n ${a} ${a@Q}\";",
418 "before before",
419 },
420 {
421 "i\x00f true; then echo before\x00; \x00fi",
422 "before\n",
423 },
424 {
425 "echo $(GOSH_CMD=foo_null_bar $GOSH_PROG)",
426 "foobar\n #IGNORE",
427 },
428 // See the TODO where foo_NULL_BAR is set.
429 // {
430 // "echo $foo_NULL_BAR \"${foo_NULL_BAR}\"",
431 // "foo\n",
432 // },
433
434 // escaped chars
435 {"echo a\\b", "ab\n"},
436 {"echo a\\ b", "a b\n"},
437 {"echo \\$a", "$a\n"},
438 {"echo \"a\\b\"", "a\\b\n"},
439 {"echo 'a\\b'", "a\\b\n"},
440 {"echo \"a\\\nb\"", "ab\n"},
441 {"echo 'a\\\nb'", "a\\\nb\n"},
442 {`echo "\""`, "\"\n"},
443 {`echo \\`, "\\\n"},
444 {`echo \\\\`, "\\\\\n"},
445 {`echo \`, "\\\n"},
446
447 // escape characters in double quote literal
448 {`echo "\\"`, "\\\n"}, // special character is preserved
449 {`echo "\b"`, "\\b\n"}, // non-special character has both characters preserved
450 {`echo "\\\\"`, "\\\\\n"}, // sequential backslashes (escape characters repeated sequentially)
451
452 // vars
453 {"foo=bar; echo $foo", "bar\n"},
454 {"foo=bar foo=etc; echo $foo", "etc\n"},
455 {"foo=bar; foo=etc; echo $foo", "etc\n"},
456 {"foo=bar; foo=; echo $foo", "\n"},
457 {"unset foo; echo $foo", "\n"},
458 {"foo=bar; unset foo; echo $foo", "\n"},
459 {"echo $INTERP_GLOBAL", "value\n"},
460 {"INTERP_GLOBAL=; echo $INTERP_GLOBAL", "\n"},
461 {"unset INTERP_GLOBAL; echo $INTERP_GLOBAL", "\n"},
462 {"echo $MIXEDCASE_INTERP_GLOBAL", "value\n"},
463 {"foo=bar; foo=x true; echo $foo", "bar\n"},
464 {"foo=bar; foo=x true; echo $foo", "bar\n"},
465 {"foo=bar; $ENV_PROG | grep '^foo='", "exit status 1"},
466 {"foo=bar $ENV_PROG | grep '^foo='", "foo=bar\n"},
467 {"foo=a foo=b $ENV_PROG | grep '^foo='", "foo=b\n"},
468 {"$ENV_PROG | grep -i '^interp_global='", "INTERP_GLOBAL=value\n"},
469 {"INTERP_GLOBAL=new; $ENV_PROG | grep -i '^interp_global='", "INTERP_GLOBAL=new\n"},
470 {"INTERP_GLOBAL=; $ENV_PROG | grep -i '^interp_global='", "INTERP_GLOBAL=\n"},
471 {"unset INTERP_GLOBAL; $ENV_PROG | grep -i '^interp_global='", "exit status 1"},
472 {"a=b; a+=c x+=y; echo $a $x", "bc y\n"},
473 {`a=" x y"; b=$a c="$a"; echo $b; echo $c`, "x y\nx y\n"},
474 {`a=" x y"; b=$a c="$a"; echo "$b"; echo "$c"`, " x y\n x y\n"},
475 {`arr=("foo" "bar" "lala" "foobar"); echo ${arr[@]:2}; echo ${arr[*]:2}`, "lala foobar\nlala foobar\n"},
476 {`arr=("foo" "bar" "lala" "foobar"); echo ${arr[@]:2:4}; echo ${arr[*]:1:4}`, "lala foobar\nbar lala foobar\n"},
477 {`arr=("foo" "bar"); echo ${arr[@]}; echo ${arr[*]}`, "foo bar\nfoo bar\n"},
478 {`arr=("foo"); echo ${arr[@]:99}`, "\n"},
479 {`echo ${arr[@]:1:99}; echo ${arr[*]:1:99}`, "\n\n"},
480 {`arr=(0 1 2 3 4 5 6 7 8 9 0 a b c d e f g h); echo ${arr[@]:3:4}`, "3 4 5 6\n"},
481
482 // quoted array slicing
483 {`a=(1 2 3 4 5); echo "${a[@]:2:2}"`, "3 4\n"},
484 {`a=(1 2 3 4 5); echo "${a[*]:2:2}"`, "3 4\n"},
485 {`a=(1 2 3 4 5); b=("${a[@]:2:2}"); echo ${#b[@]}`, "2\n"},
486 {`a=(1 2 3 4 5); echo "${a[@]:3}"`, "4 5\n"},
487 {`a=(1 2 3 4 5); echo "${a[@]: -2}"`, "4 5\n"},
488 {`a=(1 2 3 4 5); echo "${a[@]: -99}"`, "\n"},
489
490 // positional parameter slicing (1-based offset, $0 at offset 0)
491 {`f() { echo "${@:2:2}"; }; f a b c d e`, "b c\n"},
492 {`f() { echo ${@:2:2}; }; f a b c d e`, "b c\n"},
493 {`f() { echo "${@:1}"; }; f a b c`, "a b c\n"},
494 {`f() { echo "${*:2:2}"; }; f a b c d e`, "b c\n"},
495 {`f() { echo "${@: -2}"; }; f a b c d e`, "d e\n"},
496 {`f() { echo "${@: -3:2}"; }; f a b c d e`, "c d\n"},
497 {`f() { echo "${@:1:0}"; }; f a b c`, "\n"},
498 {`f() { echo "${@:99}"; }; f a b c`, "\n"},
499 {`set -- a b c; v=("${@:0:2}"); echo "${#v[@]}"`, "2\n"},
500 {`f() { for x in "${@:2:2}"; do echo "$x"; done; }; f a b c d e`, "b\nc\n"},
501 {`set --; v=("${@:0}"); echo "${#v[@]}"`, "1\n"},
502 {`f() { echo "${@: -10}"; }; f a b c`, "\n"},
503
504 {`echo ${foo[@]}; echo ${foo[*]}`, "\n\n"},
505 // TODO: reenable once we figure out the broken pipe error
506 //{`$ENV_PROG | while read line; do if test -z "$line"; then echo empty; fi; break; done`, ""}, // never begin with an empty element
507
508 // inline variables have special scoping
509 {
510 "f() { echo $inline; inline=bar true; echo $inline; }; inline=foo f",
511 "foo\nfoo\n",
512 },
513 {"v=x; read v <<< 'y'; echo $v", "y\n"},
514 {"v=x; v=inline read v <<< 'y'; echo $v", "x\n"},
515 {"v=x; v=inline unset v; echo $v", "x\n"},
516 {"v=x; echo 'v=y' >f; v=inline source ./f; echo $v", "x\n"},
517 {"declare -n v=v2; v=inline true; echo $v $v2", "\n"},
518 {"f() { echo $v; }; v=x; v=y f; f", "y\nx\n"},
519 {"f() { echo $v; }; v=x; v+=y f; f", "xy\nx\n"},
520 {"f() { echo $v; }; declare -n v=v2; v2=x; v=y f; f", "y\nx\n"},
521 {"f() { echo ${v[@]}; }; v=(e1 e2); v=y f; f", "y\ne1 e2\n"},
522
523 // special vars
524 {"echo $?; false; echo $?", "0\n1\n"},
525 {"for i in 1 2; do\necho $LINENO\necho $LINENO\ndone", "2\n3\n2\n3\n"},
526 {"[[ -n $$ && $$ -gt 0 ]]", ""},
527 {"case $- in *e*) echo yes ;; *) echo no ;; esac", "no\n"},
528 {"set -e; case $- in *e*) echo yes ;; *) echo no ;; esac", "yes\n"},
529 // Bash's $- also holds flags which we don't support, such as h and B.
530 {"set -aefu; echo $-", "aefu\n #IGNORE"},
531 {"[[ $$ -eq $PPID ]]", "exit status 1"},
532 {"[[ $RANDOM -eq $RANDOM ]]", "exit status 1"}, // 1 in 32k chance of a collision, 0.003%
533 {
534 // Assigning to RANDOM seeds it, so the sequence repeats.
535 "RANDOM=42; a=$RANDOM$RANDOM; RANDOM=42; b=$RANDOM$RANDOM; [[ $a == $b ]]",
536 "",
537 },
538 {
539 "RANDOM=1; a=$RANDOM; RANDOM=2; b=$RANDOM; [[ $a != $b ]]",
540 "",
541 },
542 {
543 // A failed assignment must not seed, so that RANDOM keeps its
544 // attributes like any other variable.
545 "readonly RANDOM; RANDOM=99; echo $?",
546 "RANDOM: readonly variable\n1\n #JUSTERR",
547 },
548 {"[[ $SRANDOM -eq $SRANDOM ]]", "exit status 1"}, // 1 in 2**32 chance of a collision,
549
550 // Ensure that we consistently use 64 bits even on 32-bit platforms.
551 // Bash doesn't do this, but we do, for portability and consistency.
552 {"[[ 1000000000123 -lt 100 ]]", "exit status 1"},
553 {"[[ 1000000000123 -eq 1000000000456 ]]", "exit status 1"},
554 {"[[ 1000000000123 < 100 ]]", "exit status 1"},
555 {"((1000000000123 == 1000000000456))", "exit status 1"},
556
557 // var manipulation
558 {"echo ${#a} ${#a[@]}", "0 0\n"},
559 {"a=bar; echo ${#a} ${#a[@]}", "3 1\n"},
560 {"a=世界; echo ${#a}", "2\n"},
561 {"a=(a bcd); echo ${#a} ${#a[@]} ${#a[*]} ${#a[1]}", "1 2 2 3\n"},
562 {
563 "a=($(echo a bcd)); echo ${#a} ${#a[@]} ${#a[*]} ${#a[1]}",
564 "1 2 2 3\n",
565 },
566 {
567 "a=([0]=$(echo a b) $(echo c d)); echo ${#a} ${#a[@]} ${#a[*]} ${#a[0]}",
568 "3 3 3 3\n",
569 },
570 {"set -- a bc; echo ${#@} ${#*} $#", "2 2 2\n"},
571 {
572 "echo ${!a}; echo more",
573 "invalid indirect expansion\nexit status 1 #JUSTERR",
574 },
575 {
576 "a=b; echo ${!a}; b=c; echo ${!a}",
577 "\nc\n",
578 },
579 {
580 "a=foo_very_long; echo ${a:1}; echo ${a: -1}; echo ${a: -10}; echo ${a:5}",
581 "oo_very_long\ng\n_very_long\nery_long\n",
582 },
583 {
584 "a=foo_very_long; echo ${a::2}; echo ${a::-1}; echo ${a: -10}; echo ${a::5}",
585 "fo\nfoo_very_lon\n_very_long\nfoo_v\n",
586 },
587 {
588 "a=abc; echo ${a:1:1}",
589 "b\n",
590 },
591 {
592 `a=héllo; echo "${a:2}" "${a:1:2}" "${a::-3}" "${a: -2}"`,
593 "llo él hé lo\n",
594 },
595 {
596 "a=foo; echo ${a/no/x} ${a/o/i} ${a//o/i} ${a/fo/}",
597 "foo fio fii o\n",
598 },
599 {
600 "a=foo; echo ${a/*/xx} ${a//?/na} ${a/o*}",
601 "xx nanana f\n",
602 },
603 {
604 "a=12345; echo ${a//[42]} ${a//[^42]} ${a//[!42]}",
605 "135 24 24\n",
606 },
607 {"a=0123456789; echo ${a//[1-35-8]}", "049\n"},
608 {"a=]abc]; echo ${a//[]b]}", "ac\n"},
609 {"a=-abc-; echo ${a//[-b]}", "ac\n"},
610 {`a='x\y'; echo ${a//\\}`, "xy\n"},
611 {"a=']'; echo ${a//[}", "]\n"},
612 {"a=']'; echo ${a//[]}", "]\n"},
613 {"a=']'; echo ${a//[]]}", "\n"},
614 {"a='['; echo ${a//[[]}", "\n"},
615 {"a=']'; echo ${a//[xy}", "]\n"},
616 {"a='abc123'; echo ${a//[[:digit:]]}", "abc\n"},
617 {"a='[[:wrong:]]'; echo ${a//[[:wrong:]]}", "[[:wrong:]]\n"},
618 {"a='[[:wrong:]]'; echo ${a//[[:}", "[[:wrong:]]\n"},
619 {"a='abcx1y'; echo ${a//x[[:digit:]]y}", "abc\n"},
620 {`a=xyz; echo "${a/y/a b}"`, "xa bz\n"},
621 {"a='foo/bar'; echo ${a//o*a/}", "fr\n"},
622 {"a=foobar; echo ${a//a/} ${a///b} ${a///}", "foobr foobar foobar\n"},
623 {
624 "echo ${a:-b}; echo $a; a=; echo ${a:-b}; a=c; echo ${a:-b}",
625 "b\n\nb\nc\n",
626 },
627 {
628 "echo ${#:-never} ${?:-never} ${LINENO:-never}",
629 "0 0 1\n",
630 },
631 {
632 "echo ${1-one} ${2-two} ${3-three}",
633 "one two three\n",
634 },
635 {
636 "set -u; echo ${1}",
637 "1: unbound variable\nexit status 1 #JUSTERR",
638 },
639 {
640 "echo ${a-b}; echo $a; a=; echo ${a-b}; a=c; echo ${a-b}",
641 "b\n\n\nc\n",
642 },
643 {
644 "echo ${a:=b}; echo $a; a=; echo ${a:=b}; a=c; echo ${a:=b}",
645 "b\nb\nb\nc\n",
646 },
647 {
648 "echo ${a=b}; echo $a; a=; echo ${a=b}; a=c; echo ${a=b}",
649 "b\nb\n\nc\n",
650 },
651 {
652 "echo ${a:+b}; echo $a; a=; echo ${a:+b}; a=c; echo ${a:+b}",
653 "\n\n\nb\n",
654 },
655 {
656 "echo ${a+b}; echo $a; a=; echo ${a+b}; a=c; echo ${a+b}",
657 "\n\nb\nb\n",
658 },
659 {
660 "a=b; echo ${a:?err1}; a=; echo ${a:?err2}; unset a; echo ${a:?err3}",
661 "b\na: err2\nexit status 1 #JUSTERR",
662 },
663 {
664 "a=b; echo ${a?err1}; a=; echo ${a?err2}; unset a; echo ${a?err3}",
665 "b\n\na: err3\nexit status 1 #JUSTERR",
666 },
667 {
668 "echo ${a:?%s}",
669 "a: %s\nexit status 1 #JUSTERR",
670 },
671 {
672 "x=aaabccc; echo ${x#*a}; echo ${x##*a}",
673 "aabccc\nbccc\n",
674 },
675 {
676 "x=(__a _b c_); echo ${x[@]#_}",
677 "_a b c_\n",
678 },
679 {
680 "x=(a__ b_ _c); echo ${x[@]%%_}",
681 "a_ b _c\n",
682 },
683 {
684 "x=aaabccc; echo ${x%c*}; echo ${x%%c*}",
685 "aaabcc\naaab\n",
686 },
687 {
688 "x=aaabccc; echo ${x%%[bc}",
689 "aaabccc\n",
690 },
691 {
692 "a='àÉñ bAr'; echo ${a^}; echo ${a^^}",
693 "ÀÉñ bAr\nÀÉÑ BAR\n",
694 },
695 {
696 "a='àÉñ bAr'; echo ${a,}; echo ${a,,}",
697 "àÉñ bAr\nàéñ bar\n",
698 },
699 {
700 "a='àÉñ bAr'; echo ${a^?}; echo ${a^^[br]}",
701 "ÀÉñ bAr\nàÉñ BAR\n",
702 },
703 {
704 "a='àÉñ bAr'; echo ${a,?}; echo ${a,,[br]}",
705 "àÉñ bAr\nàÉñ bAr\n",
706 },
707 {
708 "a=foo; echo ${a^o} ${a^f}; a=OOF; echo ${a,O} ${a,,O} ${a,o}",
709 "foo Foo\noOF ooF OOF\n",
710 },
711 {
712 "a=(àÉñ bAr); echo ${a[@]^}; echo ${a[*],,}",
713 "ÀÉñ BAr\nàéñ bar\n",
714 },
715 {
716 `a=(foo boo); printf '[%s]' "${a[@]%o}"; echo; printf '[%s]' "${a[@]/o/O}"; echo; printf '[%s]' "${a[@]^}"; echo`,
717 "[fo][bo]\n[fOo][bOo]\n[Foo][Boo]\n",
718 },
719 {
720 `set -- foo boo; printf '[%s]' "${@#?}"; echo; IFS=,; echo "${*%o}"`,
721 "[oo][oo]\nfo,bo\n",
722 },
723 {
724 `a=(foo boo); IFS=,; echo "${a[*]%o}"`,
725 "fo,bo\n",
726 },
727 {
728 `a=(aax abx); echo ${a[@]/x/}; b=("${a[@]/a/z}"); echo "${b[0]}" "${b[1]}"`,
729 "aa ab\nzax zbx\n",
730 },
731 {
732 "a=(foo boo); echo ${a[@]%o}; echo ${a[@]}",
733 "fo bo\nfoo boo\n",
734 },
735 {
736 "INTERP_X_1=a INTERP_X_2=b; echo ${!INTERP_X_*}",
737 "INTERP_X_1 INTERP_X_2\n",
738 },
739 {
740 "INTERP_X_2=b INTERP_X_1=a; echo ${!INTERP_*}",
741 "INTERP_GLOBAL INTERP_X_1 INTERP_X_2\n",
742 },
743 {
744 `INTERP_X_2=b INTERP_X_1=a; set -- ${!INTERP_*}; echo $#`,
745 "3\n",
746 },
747 {
748 `INTERP_X_2=b INTERP_X_1=a; set -- "${!INTERP_*}"; echo $#`,
749 "1\n",
750 },
751 {
752 `INTERP_X_2=b INTERP_X_1=a; set -- ${!INTERP_@}; echo $#`,
753 "3\n",
754 },
755 {
756 `INTERP_X_2=b INTERP_X_1=a; set -- "${!INTERP_@}"; echo $#`,
757 "3\n",
758 },
759 {
760 `a='b c'; eval "echo -n ${a} ${a@Q}"`,
761 `b c b c`,
762 },
763 {
764 `a='"\n'; printf "%s %s" "${a}" "${a@E}"`,
765 "\"\\n \"\n",
766 },
767
768 // ${var@a} and ${var@A}
769 {
770 `a=foo; echo "<${a@a}>"`,
771 "<>\n",
772 },
773 {
774 `declare -a arr=(1 2 3); echo "${arr@a}"`,
775 "a\n",
776 },
777 {
778 `declare -A map=([k]=v); echo "${map@a}"`,
779 "A\n",
780 },
781 {
782 `export e=1; echo "${e@a}"`,
783 "x\n",
784 },
785 {
786 `readonly ro=1; echo "${ro@a}"`,
787 "r\n",
788 },
789 {
790 `declare -a arr=(1); export arr; echo "${arr@a}"`,
791 "ax\n",
792 },
793 {
794 `a=hello; echo "${a@A}"`,
795 "a=hello\n #IGNORE bash always single-quotes",
796 },
797 {
798 `export e=1; echo "${e@A}"`,
799 "declare -x e=1\n #IGNORE bash always single-quotes",
800 },
801 {
802 `a=Hello; echo "${a@U}"`,
803 "HELLO\n",
804 },
805 {
806 `a=hello; echo "${a@u}"`,
807 "Hello\n",
808 },
809 {
810 `a=HELLO; echo "${a@L}"`,
811 "hello\n",
812 },
813 {
814 `a=foo; echo "<${a@K}><${a@k}>"`,
815 "<foo><foo>\n #IGNORE not implemented; must not panic",
816 },
817 {
818 "declare a; a+=(b); echo ${a[@]} ${#a[@]}",
819 "b 1\n",
820 },
821 {
822 `a=""; a+=(b); echo ${a[@]} ${#a[@]}`,
823 "b 2\n",
824 },
825 {
826 "f() { local a; a=bad; a=good; echo $a; }; f",
827 "good\n",
828 },
829 {
830 `declare x; [[ -v x ]] && echo set || echo unset`,
831 "unset\n",
832 },
833 {
834 `declare x=; [[ -v x ]] && echo set || echo unset`,
835 "set\n",
836 },
837 {
838 `declare -a x; [[ -v x ]] && echo set || echo unset`,
839 "unset\n",
840 },
841 {
842 `declare -A x; [[ -v x ]] && echo set || echo unset`,
843 "unset\n",
844 },
845 {
846 `declare -r -x x; [[ -v x ]] && echo set || echo unset`,
847 "unset\n",
848 },
849 {
850 `declare -n x; [[ -v x ]] && echo set || echo unset`,
851 "unset\n",
852 },
853
854 // declare -f and declare -p
855 {
856 `f() { echo hello; }; declare -f f`,
857 "f()\n{ echo hello; }\n #IGNORE output format differs from bash",
858 },
859 {
860 `declare -f nonexistent 2>/dev/null; echo "exit: $?"`,
861 "exit: 1\n",
862 },
863 {
864 `f() { echo hello; }; declare -f f >/dev/null && echo "f exists"`,
865 "f exists\n",
866 },
867 {
868 `a=hello; declare -p a`,
869 "declare -- a=\"hello\"\n",
870 },
871 {
872 `declare -a arr=(1 2 3); declare -p arr`,
873 "declare -a arr=([0]=\"1\" [1]=\"2\" [2]=\"3\")\n",
874 },
875 {
876 `export e=1; declare -p e`,
877 "declare -x e=\"1\"\n",
878 },
879 {
880 `readonly c=immutable; declare -p c`,
881 "declare -r c=\"immutable\"\n",
882 },
883 {
884 `declare -p nonexistent 2>/dev/null; echo "exit: $?"`,
885 "exit: 1\n",
886 },
887
888 // if
889 {
890 "if true; then echo foo; fi",
891 "foo\n",
892 },
893 {
894 "if false; then echo foo; fi",
895 "",
896 },
897 {
898 "if GOSH_CMD=print_fail $GOSH_PROG; then echo foo; fi",
899 "exec fail\n",
900 },
901 {
902 "if true; then echo foo; else echo bar; fi",
903 "foo\n",
904 },
905 {
906 "if false; then echo foo; else echo bar; fi",
907 "bar\n",
908 },
909 {
910 "if true; then false; fi",
911 "exit status 1",
912 },
913 {
914 "if false; then :; else false; fi",
915 "exit status 1",
916 },
917 {
918 "if false; then :; elif true; then echo foo; fi",
919 "foo\n",
920 },
921 {
922 "if false; then :; elif false; then :; elif true; then echo foo; fi",
923 "foo\n",
924 },
925 {
926 "if false; then :; elif false; then :; else echo foo; fi",
927 "foo\n",
928 },
929
930 // while
931 {
932 "while false; do echo foo; done",
933 "",
934 },
935 {
936 "while GOSH_CMD=print_fail $GOSH_PROG; do echo foo; done",
937 "exec fail\n",
938 },
939 {
940 "while true; do exit 1; done",
941 "exit status 1",
942 },
943 {
944 "while true; do break; done",
945 "",
946 },
947 {
948 "while true; do while true; do break 2; done; done",
949 "",
950 },
951
952 // until
953 {
954 "until true; do echo foo; done",
955 "",
956 },
957 {
958 "until false; do exit 1; done",
959 "exit status 1",
960 },
961 {
962 "until false; do break; done",
963 "",
964 },
965
966 // for
967 {
968 "for i in 1 2 3; do echo $i; done",
969 "1\n2\n3\n",
970 },
971 {
972 "for i in 1 2 3; do echo $i; exit; done",
973 "1\n",
974 },
975 {
976 "for i in 1 2 3; do echo $i; false; done",
977 "1\n2\n3\nexit status 1",
978 },
979 {
980 "for i in 1 2 3; do echo $i; break; done",
981 "1\n",
982 },
983 {
984 "for i in 1 2 3; do echo $i; continue; echo foo; done",
985 "1\n2\n3\n",
986 },
987 {
988 "for i in 1 2; do for j in a b; do echo $i $j; continue 2; done; done",
989 "1 a\n2 a\n",
990 },
991 {
992 "for ((i=0; i<3; i++)); do echo $i; done",
993 "0\n1\n2\n",
994 },
995 // for, with missing Init, Cond, Post
996 {
997 "i=0; for ((; i<3; i++)); do echo $i; done",
998 "0\n1\n2\n",
999 },
1000 {
1001 "for ((i=0;; i++)); do if [ $i -ge 3 ]; then break; fi; echo $i; done",
1002 "0\n1\n2\n",
1003 },
1004 {
1005 "for ((i=0; i<3;)); do echo $i; i=$((i+1)); done",
1006 "0\n1\n2\n",
1007 },
1008 {
1009 "i=0; for ((;;)); do if [ $i -ge 3 ]; then break; fi; echo $i; i=$((i+1)); done",
1010 "0\n1\n2\n",
1011 },
1012 {
1013 "readonly i; for ((i=0; i<3; i++)); do echo $i; done",
1014 "i: readonly variable\nexit status 1 #JUSTERR",
1015 },
1016 {
1017 "readonly i; ((i=3)); echo $?; echo $i",
1018 "i: readonly variable\n1\n\n #JUSTERR",
1019 },
1020 {
1021 "for ((i=5; i>0; i--)); do echo $i; break; done",
1022 "5\n",
1023 },
1024 {
1025 "for i in 1 2; do for j in a b; do echo $i $j; done; break; done",
1026 "1 a\n1 b\n",
1027 },
1028 {
1029 "for i in 1 2 3; do :; done; echo $i",
1030 "3\n",
1031 },
1032 {
1033 "for ((i=0; i<3; i++)); do :; done; echo $i",
1034 "3\n",
1035 },
1036 {
1037 "set -- a 'b c'; for i in; do echo $i; done",
1038 "",
1039 },
1040 {
1041 "set -- a 'b c'; for i; do echo $i; done",
1042 "a\nb c\n",
1043 },
1044
1045 // block
1046 {
1047 "{ echo foo; }",
1048 "foo\n",
1049 },
1050 {
1051 "{ false; }",
1052 "exit status 1",
1053 },
1054
1055 // subshell
1056 {
1057 "(echo foo)",
1058 "foo\n",
1059 },
1060 {
1061 "(false)",
1062 "exit status 1",
1063 },
1064 {
1065 "(exit 1)",
1066 "exit status 1",
1067 },
1068 {
1069 "(false); echo foo",
1070 "foo\n",
1071 },
1072 {
1073 "(exit 0); echo foo",
1074 "foo\n",
1075 },
1076 {
1077 "(exit 1); echo foo",
1078 "foo\n",
1079 },
1080 {
1081 "(foo=bar; echo $foo); echo $foo",
1082 "bar\n\n",
1083 },
1084 {
1085 "(echo() { printf 'bar\n'; }; echo); echo",
1086 "bar\n\n",
1087 },
1088 {
1089 "unset INTERP_GLOBAL & echo $INTERP_GLOBAL",
1090 "value\n",
1091 },
1092 {
1093 "(fn() { :; }) & pwd >/dev/null",
1094 "",
1095 },
1096 {
1097 "x[0]=x; (echo ${x[0]}; x[0]=y; echo ${x[0]}); echo ${x[0]}",
1098 "x\ny\nx\n",
1099 },
1100 {
1101 `x[3]=x; (x[3]=y); echo ${x[3]}`,
1102 "x\n",
1103 },
1104 {
1105 "shopt -s expand_aliases; alias f='echo x'\nf\n(f\nalias f='echo y'\neval f\n)\nf\n",
1106 "x\nx\ny\nx\n",
1107 },
1108 {
1109 "set -- a; echo $1; (echo $1; set -- b; echo $1); echo $1",
1110 "a\na\nb\na\n",
1111 },
1112 {"false; ( echo $? )", "1\n"},
1113
1114 // cd/pwd
1115 {"[[ fo~ == 'fo~' ]]", ""},
1116 {`[[ 'ab\c' == *\\* ]]`, ""},
1117 {`[[ foo/bar == foo* ]]`, ""},
1118 {"[[ a == [ab ]]", "exit status 1"},
1119 {`HOME='/*'; echo ~; echo "$HOME"`, "/*\n/*\n"},
1120 {`test -d ~`, ""},
1121 {
1122 `for flag in b c d e f g h k L p r s S u w x; do test -$flag ""; echo -n "$flag$? "; done`,
1123 `b1 c1 d1 e1 f1 g1 h1 k1 L1 p1 r1 s1 S1 u1 w1 x1 `,
1124 },
1125 {`foo=~; test -d $foo`, ""},
1126 {`foo=~; test -d "$foo"`, ""},
1127 {`foo='~'; test -d $foo`, "exit status 1"},
1128 {`foo='~'; [ $foo == '~' ]`, ""},
1129 {
1130 `[[ ~ == "$HOME" ]] && [[ ~/foo == "$HOME/foo" ]]`,
1131 "",
1132 },
1133 {
1134 `HOME=$PWD/home; mkdir home; touch home/f; [[ -e ~/f ]]`,
1135 "",
1136 },
1137 {
1138 `HOME=$PWD/home; mkdir home; touch home/f; [[ ~/f -ef $HOME/f ]]`,
1139 "",
1140 },
1141 {
1142 "[[ ~noexist == '~noexist' ]]",
1143 "",
1144 },
1145 {
1146 `w="$HOME"; cd; [[ $PWD == "$w" ]]`,
1147 "",
1148 },
1149 {
1150 `cd ''`,
1151 "cd: empty directory path\nexit status 1 #JUSTERR",
1152 },
1153 {
1154 `HOME=/foo; echo $HOME`,
1155 "/foo\n",
1156 },
1157 {
1158 "cd noexist",
1159 "cd: no such file or directory: \"noexist\"\nexit status 1 #JUSTERR",
1160 },
1161 {
1162 "mkdir -p a/b && cd a && cd b && cd ../..",
1163 "",
1164 },
1165 {
1166 ">a && cd a",
1167 "cd: no such file or directory: \"a\"\nexit status 1 #JUSTERR",
1168 },
1169 {
1170 `[[ $PWD == "$(pwd)" ]]`,
1171 "",
1172 },
1173 {
1174 "PWD=changed; [[ $PWD == changed ]]",
1175 "",
1176 },
1177 {
1178 "PWD=changed; mkdir a; cd a; [[ $PWD == changed ]]",
1179 "exit status 1",
1180 },
1181 {
1182 `mkdir %s; old="$PWD"; cd %s; [[ $old == "$PWD" ]]`,
1183 "exit status 1",
1184 },
1185 {
1186 `old="$PWD"; mkdir a; cd a; cd ..; [[ $old == "$PWD" ]]`,
1187 "",
1188 },
1189 {
1190 `[[ $PWD == "$OLDPWD" ]]`,
1191 "exit status 1",
1192 },
1193 {
1194 `old="$PWD"; mkdir a; cd a; [[ $old == "$OLDPWD" ]]`,
1195 "",
1196 },
1197 {
1198 // Note that absolute paths need cleaning too, not just relative ones.
1199 // Compare against a relative cd to avoid depending on the separator.
1200 `mkdir -p a b; cd b; ref=$PWD; cd ..; cd $PWD/a/../b; [[ $PWD == "$ref" ]]`,
1201 "",
1202 },
1203 {
1204 `mkdir a; ln -s a b; [[ $(cd a && pwd) == "$(cd b && pwd)" ]]; echo $?`,
1205 "1\n",
1206 },
1207 {
1208 `pwd -a`,
1209 "invalid option: \"-a\"\nexit status 2 #JUSTERR",
1210 },
1211 {
1212 `pwd -L -P -a`,
1213 "invalid option: \"-a\"\nexit status 2 #JUSTERR",
1214 },
1215 {
1216 `mkdir a; ln -s a b; [[ "$(cd a && pwd -P)" == "$(cd b && pwd -P)" ]]`,
1217 "",
1218 },
1219 {
1220 `mkdir a; ln -s a b; [[ "$(cd a && pwd -P)" == "$(cd b && pwd -L)" ]]; echo $?`,
1221 "1\n",
1222 },
1223 {
1224 `orig="$PWD"; mkdir a; cd a; cd - >/dev/null; [[ "$PWD" == "$orig" ]]`,
1225 "",
1226 },
1227 {
1228 `orig="$PWD"; mkdir a; cd a; [[ $(cd -) == "$orig" ]]`,
1229 "",
1230 },
1231
1232 // dirs/pushd/popd
1233 {"set -- $(dirs); echo $# ${#DIRSTACK[@]}", "1 1\n"},
1234 {"pushd", "pushd: no other directory\nexit status 1 #JUSTERR"},
1235 {"pushd -n", ""},
1236 {"pushd foo bar", "pushd: too many arguments\nexit status 2 #JUSTERR"},
1237 {"pushd does-not-exist; set -- $(dirs); echo $#", "pushd: no such file or directory: \"does-not-exist\"\n1\n #IGNORE"},
1238 {"mkdir a; pushd a >/dev/null; set -- $(dirs); echo $#", "2\n"},
1239 {"mkdir a; set -- $(pushd a); echo $#", "2\n"},
1240 {
1241 `mkdir a; pushd a >/dev/null; set -- $(dirs); [[ $1 == "$HOME" ]]`,
1242 "exit status 1",
1243 },
1244 {
1245 `mkdir a; pushd a >/dev/null; [[ ${DIRSTACK[0]} == "$HOME" ]]`,
1246 "exit status 1",
1247 },
1248 {
1249 `old=$(dirs); mkdir a; pushd a >/dev/null; pushd >/dev/null; set -- $(dirs); [[ $1 == "$old" ]]`,
1250 "",
1251 },
1252 {
1253 `old=$(dirs); mkdir a; pushd a >/dev/null; pushd -n >/dev/null; set -- $(dirs); [[ $1 == "$old" ]]`,
1254 "exit status 1",
1255 },
1256 {
1257 "mkdir a; pushd a >/dev/null; pushd >/dev/null; rm -r a; pushd",
1258 "pushd: no such file or directory: ABS_PATH_A\nexit status 1 #JUSTERR",
1259 },
1260 {
1261 `old=$(dirs); mkdir a; pushd -n a >/dev/null; set -- $(dirs); [[ $1 == "$old" ]]`,
1262 "",
1263 },
1264 {
1265 `old=$(dirs); mkdir a; pushd -n a >/dev/null; pushd >/dev/null; set -- $(dirs); [[ $1 == "$old" ]]`,
1266 "exit status 1",
1267 },
1268 {"popd", "popd: directory stack empty\nexit status 1 #JUSTERR"},
1269 {"popd -n", "popd: directory stack empty\nexit status 1 #JUSTERR"},
1270 {"popd foo", "popd: invalid argument\nexit status 2 #JUSTERR"},
1271 {"old=$(dirs); mkdir a; pushd a >/dev/null; set -- $(popd); echo $#", "1\n"},
1272 {
1273 `old=$(dirs); mkdir a; pushd a >/dev/null; popd >/dev/null; [[ $(dirs) == "$old" ]]`,
1274 "",
1275 },
1276 {"old=$(dirs); mkdir a; pushd a >/dev/null; set -- $(popd -n); echo $#", "1\n"},
1277 {
1278 `old=$(dirs); mkdir a; pushd a >/dev/null; popd -n >/dev/null; [[ $(dirs) == "$old" ]]`,
1279 "exit status 1",
1280 },
1281 {
1282 "mkdir a; pushd a >/dev/null; pushd >/dev/null; rm -r a; popd",
1283 "popd: no such file or directory: ABS_PATH_A\nexit status 1 #JUSTERR",
1284 },
1285
1286 // binary cmd
1287 {
1288 "true && echo foo || echo bar",
1289 "foo\n",
1290 },
1291 {
1292 "false && echo foo || echo bar",
1293 "bar\n",
1294 },
1295
1296 // func
1297 {
1298 "foo() { echo bar; }; foo",
1299 "bar\n",
1300 },
1301 {
1302 "foo() { echo $1; }; foo",
1303 "\n",
1304 },
1305 {
1306 "foo() { echo $1; }; foo a b",
1307 "a\n",
1308 },
1309 {
1310 "foo() { echo $1; bar c d; echo $2; }; bar() { echo $2; }; foo a b",
1311 "a\nd\nb\n",
1312 },
1313 {
1314 `foo() { echo $#; }; foo; foo 1 2 3; foo "a b"; echo $#`,
1315 "0\n3\n1\n0\n",
1316 },
1317 {
1318 `foo() { for a in $*; do echo "$a"; done }; foo 'a 1' 'b 2'`,
1319 "a\n1\nb\n2\n",
1320 },
1321 {
1322 `foo() { for a in "$*"; do echo "$a"; done }; foo 'a 1' 'b 2'`,
1323 "a 1 b 2\n",
1324 },
1325 {
1326 `foo() { for a in "foo$*"; do echo "$a"; done }; foo 'a 1' 'b 2'`,
1327 "fooa 1 b 2\n",
1328 },
1329 {
1330 `foo() { for a in $@; do echo "$a"; done }; foo 'a 1' 'b 2'`,
1331 "a\n1\nb\n2\n",
1332 },
1333 {
1334 `foo() { for a in "$@"; do echo "$a"; done }; foo 'a 1' 'b 2'`,
1335 "a 1\nb 2\n",
1336 },
1337
1338 // alias (note the input newlines)
1339 {
1340 "alias foo; alias foo=echo; alias foo; alias foo=; alias foo",
1341 "alias: \"foo\" not found\nalias foo='echo'\nalias foo=''\n #IGNORE",
1342 },
1343 {
1344 "shopt -s expand_aliases; alias foo=echo\nfoo foo; foo bar",
1345 "foo\nbar\n",
1346 },
1347 {
1348 "shopt -s expand_aliases; alias true=echo\ntrue foo; unalias true\ntrue bar",
1349 "foo\n",
1350 },
1351 {
1352 "shopt -s expand_aliases; alias echo='echo a'\necho b c",
1353 "a b c\n",
1354 },
1355 {
1356 "shopt -s expand_aliases; alias foo='echo '\nfoo foo; foo bar",
1357 "echo\nbar\n",
1358 },
1359
1360 // case
1361 {
1362 "case b in x) echo foo ;; a|b) echo bar ;; esac",
1363 "bar\n",
1364 },
1365 {
1366 "case b in x) echo foo ;; y|z) echo bar ;; esac",
1367 "",
1368 },
1369 {
1370 "case foo in bar) echo foo ;; *) echo bar ;; esac",
1371 "bar\n",
1372 },
1373 {
1374 "case foo in *o*) echo bar ;; esac",
1375 "bar\n",
1376 },
1377 {
1378 "case foo in '*') echo x ;; f*) echo y ;; esac",
1379 "y\n",
1380 },
1381 {
1382 `case 0 in [\0]) echo bar ;; esac`,
1383 "bar\n",
1384 },
1385 {
1386 `case d in [\d]) echo bar ;; esac`,
1387 "bar\n",
1388 },
1389 {
1390 `case '[' in [) echo match ;; *) echo miss ;; esac`,
1391 "match\n",
1392 },
1393 {
1394 `case '[abc' in [a*) echo match ;; *) echo miss ;; esac`,
1395 "match\n",
1396 },
1397 {
1398 "case ab in a*) echo one ;& *b) echo two ;; esac",
1399 "one\ntwo\n",
1400 },
1401 {
1402 "case ab in a*) echo one ;;& *b) echo two ;; esac",
1403 "one\ntwo\n",
1404 },
1405 {
1406 "case ab in a*) echo one ;;& *zz) echo two ;; esac",
1407 "one\n",
1408 },
1409 {
1410 "case ab in a*) echo one ;& *zz) echo two ;; esac",
1411 "one\ntwo\n",
1412 },
1413 {
1414 "case ab in a*) echo one ;& *zz) echo two ;& *) echo three ;; esac",
1415 "one\ntwo\nthree\n",
1416 },
1417 {
1418 "f() { case ab in a*) echo one; return ;& *) echo two ;; esac; }; f; echo end",
1419 "one\nend\n",
1420 },
1421 {
1422 `touch a b; x=']'; echo [ab$x`,
1423 "a b\n",
1424 },
1425
1426 // exec
1427 {
1428 "$GOSH_PROG 'echo foo'",
1429 "foo\n",
1430 },
1431 {
1432 "$GOSH_PROG 'echo foo >&2' >/dev/null",
1433 "foo\n",
1434 },
1435 {
1436 "echo foo | $GOSH_PROG 'cat >&2' >/dev/null",
1437 "foo\n",
1438 },
1439 {
1440 "$GOSH_PROG 'exit 1'",
1441 "exit status 1",
1442 },
1443 {
1444 "exec >/dev/null; echo foo",
1445 "",
1446 },
1447 {
1448 "exec >a; echo foo; cat a >&2",
1449 "foo\n",
1450 },
1451 {
1452 "exec >a; echo one >b; echo two; cat a b >&2",
1453 "two\none\n",
1454 },
1455 {
1456 "{ exec >a; echo in; } >b; echo out; cat a b >&2",
1457 "out\nin\n",
1458 },
1459
1460 // return
1461 {"return", "return: can only be done from a func or sourced script\nexit status 1 #JUSTERR"},
1462 {"f() { return; }; f", ""},
1463 {"f() { return 2; }; f", "exit status 2"},
1464 {"f() { echo foo; return; echo bar; }; f", "foo\n"},
1465 {"f1() { :; }; f2() { f1; return; }; f2", ""},
1466 {"echo 'return' >a; source ./a", ""},
1467 {"echo 'return' >a; source ./a; return", "return: can only be done from a func or sourced script\nexit status 1 #JUSTERR"},
1468 {"echo 'return 2' >a; source ./a", "exit status 2"},
1469 {"echo 'echo foo; return; echo bar' >a; source ./a", "foo\n"},
1470
1471 // command
1472 {"command", ""},
1473 {"command -o echo", "command: invalid option \"-o\"\nexit status 2 #JUSTERR"},
1474 {"command -vo echo", "command: invalid option \"-o\"\nexit status 2 #JUSTERR"},
1475 {"echo() { :; }; echo foo", ""},
1476 {"echo() { :; }; command echo foo", "foo\n"},
1477 {"command -v does-not-exist", "exit status 1"},
1478 {"foo() { :; }; command -v foo", "foo\n"},
1479 {"foo() { :; }; command -v does-not-exist foo", "foo\n"},
1480 {"command -v echo", "echo\n"},
1481 {"[[ $(command -v $PATH_PROG) == $PATH_PROG ]]", "exit status 1"},
1482
1483 // cmd substitution
1484 {
1485 "echo foo $(printf bar)",
1486 "foo bar\n",
1487 },
1488 {
1489 "echo foo $(echo bar)",
1490 "foo bar\n",
1491 },
1492 {
1493 "$(echo echo foo bar)",
1494 "foo bar\n",
1495 },
1496 {
1497 "for i in 1 $(echo 2 3) 4; do echo $i; done",
1498 "1\n2\n3\n4\n",
1499 },
1500 {
1501 "echo 1$(echo 2 3)4",
1502 "12 34\n",
1503 },
1504 {
1505 `mkdir d; [[ $(cd d && pwd) == "$(pwd)" ]]`,
1506 "exit status 1",
1507 },
1508 {
1509 "a=sub true & { a=main $ENV_PROG | grep '^a='; }",
1510 "a=main\n",
1511 },
1512 {
1513 "echo foo >f; echo $(cat f); echo $(<f)",
1514 "foo\nfoo\n",
1515 },
1516 {
1517 "echo foo >f; echo $(<f; echo bar)",
1518 "bar\n",
1519 },
1520 {
1521 "$(false); echo $?; $(exit 3); echo $?; $(true); echo $?",
1522 "1\n3\n0\n",
1523 },
1524 {
1525 "foo=$(false); echo $?; echo foo $(false); echo $?",
1526 "1\nfoo\n0\n",
1527 },
1528 {
1529 "$(false) $(true); echo $?; $(true) $(false); echo $?",
1530 "0\n1\n",
1531 },
1532 {
1533 "foo=$(false) $(true); echo $?; foo=$(true) $(false); echo $?",
1534 "1\n0\n",
1535 },
1536
1537 // pipes
1538 {
1539 "echo foo | sed 's/o/a/g'",
1540 "faa\n",
1541 },
1542 {
1543 "echo foo | false | true",
1544 "",
1545 },
1546 {
1547 "true $(true) | true", // used to panic
1548 "",
1549 },
1550 {
1551 // The first command in the block used to consume stdin, even
1552 // though it shouldn't be. We just want to run any arbitrary
1553 // non-builtin program that doesn't consume stdin.
1554 "echo foo | { $ENV_PROG >/dev/null; cat; }",
1555 "foo\n",
1556 },
1557
1558 // redirects
1559 {
1560 "echo foo >&5",
1561 "unhandled >& arg: \"5\"\nexit status 1 #JUSTERR",
1562 },
1563 {
1564 "echo foo 5>a",
1565 "unsupported redirect fd: 5\nexit status 1 #IGNORE",
1566 },
1567 {
1568 "echo foo >|a",
1569 "unhandled redirect op: >|\nexit status 1 #IGNORE",
1570 },
1571 {
1572 "echo foo >a; read -r line <>a",
1573 "unhandled redirect op: <>\nexit status 1 #IGNORE",
1574 },
1575 {
1576 "echo foo >&1 | sed 's/o/a/g'",
1577 "faa\n",
1578 },
1579 {
1580 "echo foo >&2 | sed 's/o/a/g'",
1581 "foo\n",
1582 },
1583 {
1584 // TODO: why does bash need a block here?
1585 "{ echo foo >&2; } |& sed 's/o/a/g'",
1586 "faa\n",
1587 },
1588 {
1589 "echo foo >/dev/null; echo bar",
1590 "bar\n",
1591 },
1592 {
1593 ">a; echo foo >>b; wc -c <a >>b; cat b | tr -d ' '",
1594 "foo\n0\n",
1595 },
1596 {
1597 "echo foo >a; <a",
1598 "",
1599 },
1600 {
1601 "echo foo >a; mkdir b; cd b; cat <../a",
1602 "foo\n",
1603 },
1604 {
1605 "echo foo >a; wc -c <a | tr -d ' '",
1606 "4\n",
1607 },
1608 {
1609 "echo foo >>a; echo bar &>>a; wc -c <a | tr -d ' '",
1610 "8\n",
1611 },
1612 {
1613 "{ echo a; echo b >&2; } &>/dev/null",
1614 "",
1615 },
1616 {
1617 "sed 's/o/a/g' <<EOF\nfoo$foo\nEOF",
1618 "faa\n",
1619 },
1620 {
1621 "sed 's/o/a/g' <<'EOF'\nfoo$foo\nEOF",
1622 "faa$faa\n",
1623 },
1624 {
1625 "sed 's/o/a/g' <<EOF\n\tfoo\nEOF",
1626 "\tfaa\n",
1627 },
1628 {
1629 "sed 's/o/a/g' <<EOF\nfoo\nEOF",
1630 "faa\n",
1631 },
1632 {
1633 "cat <<EOF\n~/foo\nEOF",
1634 "~/foo\n",
1635 },
1636 {
1637 "sed 's/o/a/g' <<<foo$foo",
1638 "faa\n",
1639 },
1640 {
1641 "cat <<-EOF\n\tfoo\nEOF",
1642 "foo\n",
1643 },
1644 {
1645 "cat <<-EOF\n\tfoo\n\nEOF",
1646 "foo\n\n",
1647 },
1648 {
1649 "cat <<EOF\nfoo\\\nbar\nEOF",
1650 "foobar\n",
1651 },
1652 {
1653 "cat <<'EOF'\nfoo\\\nbar\nEOF",
1654 "foo\\\nbar\n",
1655 },
1656 {
1657 "cat <<'EOF'\nback\\\\slash dollar\\$x tick\\`y\nEOF",
1658 "back\\\\slash dollar\\$x tick\\`y\n",
1659 },
1660 {
1661 "cat <<-'EOF'\n\ttab\\$stripped\n\tEOF",
1662 "tab\\$stripped\n",
1663 },
1664 {
1665 "cat <<\\EOF\ndollar\\$x\nEOF",
1666 "dollar\\$x\n",
1667 },
1668 {
1669 "cat <<'EOF'\n$HOME `echo hi` $(echo hi) $((1+1))\nEOF",
1670 "$HOME `echo hi` $(echo hi) $((1+1))\n",
1671 },
1672 {
1673 "cat <<\"EOF\"\ndollar\\$x\nEOF",
1674 "dollar\\$x\n",
1675 },
1676 {
1677 "cat <<EOF\nEOF",
1678 "",
1679 },
1680 {
1681 "cat <<'EOF'\nEOF",
1682 "",
1683 },
1684 {
1685 "cat <<-EOF\n\tEOF",
1686 "",
1687 },
1688 {
1689 "cat <<EOF\nfoo\\\"bar\\baz\nEOF",
1690 "foo\\\"bar\\baz\n",
1691 },
1692 {
1693 "cat <<EOF\n \\\\ \\$ \\` \nEOF",
1694 " \\ $ ` \n",
1695 },
1696 {
1697 // The error message is capitalized on some platforms, such as js.
1698 "mkdir a; echo foo >a |& grep -q -i 'is a directory'",
1699 " #IGNORE bash prints a warning",
1700 },
1701 {
1702 "echo foo 1>&1 | sed 's/o/a/g'",
1703 "faa\n",
1704 },
1705 {
1706 "echo foo 2>&2 |& sed 's/o/a/g'",
1707 "faa\n",
1708 },
1709 {
1710 "printf 2>&1 | sed 's/.*usage.*/foo/'",
1711 "foo\n",
1712 },
1713 {
1714 "mkdir a && cd a && echo foo >b && cd .. && cat a/b",
1715 "foo\n",
1716 },
1717 {
1718 "echo foo 2>&-; :",
1719 "foo\n",
1720 },
1721 {
1722 // `>&-` closes stdout or stderr. Note that any writes result in errors.
1723 "echo foo >&- 2>&-; :",
1724 "",
1725 },
1726 {
1727 "echo foo | sed $(read line 2>/dev/null; echo 's/o/a/g')",
1728 "",
1729 },
1730 {
1731 // `<&-` closes stdin, to e.g. ensure that a subshell does not consume
1732 // the standard input shared with the parent shell.
1733 // Note that any reads result in errors.
1734 "echo foo | sed $(exec <&-; read line 2>/dev/null; echo 's/o/a/g')",
1735 "faa\n",
1736 },
1737 {
1738 // Concurrent pipe commands used to cause races when modifying the environment.
1739 "a=1 b=2 c=3 d=4 e=5 : | a=1 b=2 c=3 d=4 e=5 : | a=1 b=2 c=3 d=4 e=5 : | a=1 b=2 c=3 d=4 e=5 :",
1740 "",
1741 },
1742
1743 // background/wait
1744 {"wait", ""},
1745 {"wait foo", "wait: pid foo is not a child of this shell\nexit status 1 #JUSTERR"},
1746 {"{ true; } & wait", ""},
1747 {"{ false; } & wait", ""},
1748 {"{ sleep 0.01; true; } & wait", ""},
1749 {"{ sleep 0.01; false; } & wait", ""},
1750 {
1751 "{ echo foo; } & wait; echo bar",
1752 "foo\nbar\n",
1753 },
1754 {
1755 "{ echo foo & wait; } & wait; echo bar",
1756 "foo\nbar\n",
1757 },
1758 {`mkdir d; old=$PWD; cd d & wait; [[ $old == "$PWD" ]]`, ""},
1759 {
1760 "f() { echo 1; }; { sleep 0.01; f; } & f() { echo 2; }; wait",
1761 "1\n",
1762 },
1763 {"[[ -n $! ]]", "exit status 1"},
1764 {"true & [[ -n $! ]]", ""},
1765 {"true & true; [[ -n $! ]]", ""},
1766 {"true & pid=$!; wait $pid", ""},
1767 {"false & pid=$!; wait $pid", "exit status 1"},
1768 {"{ sleep 0.01; true; } & pid=$!; wait $pid", ""},
1769 {"{ sleep 0.01; false; } & pid=$!; wait $pid", "exit status 1"},
1770 {"(true) & ok=$!; (false) & fail=$!; wait $ok $fail", "exit status 1"},
1771 {"(true) & ok=$!; (false) & ignore=$!; wait $ok", ""},
1772 {"echo foo | true | false & wait $!", "exit status 1"},
1773 {"echo foo | false | true & wait $!", ""},
1774 {"f() { false & true; }; f; wait $!", "exit status 1"},
1775 // The parent and child shells should not cause data races when setting env vars.
1776 // Note that we can't use `echo $var`, as it seems to write newlines separately,
1777 // which can cause them to get mixed up between concurrent subshells.
1778 {
1779 "{ for n in {0..9}; do { echo -n $n$'\n'; } & done; wait; } | sort",
1780 "0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n",
1781 },
1782 {
1783 "outer=val; for n in {0..9}; do { echo -n $outer$'\n'; } & outer=val; done; wait",
1784 "val\nval\nval\nval\nval\nval\nval\nval\nval\nval\n",
1785 },
1786 {
1787 "for n in {0..9}; do { inner=val; } & echo $inner; done",
1788 "\n\n\n\n\n\n\n\n\n\n",
1789 },
1790 {
1791 "exit 2 & bg1=$!; exit 0 & bg2=$!; wait $bg1 $bg2; echo $?",
1792 "0\n",
1793 },
1794 {
1795 "exit 2 & bg1=$!; exit 4 & bg2=$!; wait $bg1 $bg2; echo $?",
1796 "4\n",
1797 },
1798
1799 // bash test
1800 {
1801 "[[ a ]]",
1802 "",
1803 },
1804 {
1805 "[[ '' ]]",
1806 "exit status 1",
1807 },
1808 {
1809 "[[ '' ]]; [[ a ]]",
1810 "",
1811 },
1812 {
1813 "[[ ! (a == b) ]]",
1814 "",
1815 },
1816 {
1817 "[[ a != b ]]",
1818 "",
1819 },
1820 {
1821 "[[ a && '' ]]",
1822 "exit status 1",
1823 },
1824 {
1825 "[[ a || '' ]]",
1826 "",
1827 },
1828 {
1829 "[[ a > 3 ]]",
1830 "",
1831 },
1832 {
1833 "[[ a < 3 ]]",
1834 "exit status 1",
1835 },
1836 {
1837 "[[ 3 == 03 ]]",
1838 "exit status 1",
1839 },
1840 {
1841 "[[ a -eq b ]]",
1842 "",
1843 },
1844 {
1845 "[[ 3 -eq 03 ]]",
1846 "",
1847 },
1848 {
1849 "[[ 3 -ne 4 ]]",
1850 "",
1851 },
1852 {
1853 "[[ 3 -le 4 ]]",
1854 "",
1855 },
1856 {
1857 "[[ 3 -ge 4 ]]",
1858 "exit status 1",
1859 },
1860 {
1861 "[[ 3 -ge 3 ]]",
1862 "",
1863 },
1864 {
1865 "[[ 3 -lt 4 ]]",
1866 "",
1867 },
1868 {
1869 "[[ ' 3' -lt '4 ' ]]",
1870 "",
1871 },
1872 {
1873 "[[ 3 -gt 4 ]]",
1874 "exit status 1",
1875 },
1876 {
1877 "[[ 3 -gt 3 ]]",
1878 "exit status 1",
1879 },
1880 {
1881 "[[ a -nt a || a -ot a ]]",
1882 "exit status 1",
1883 },
1884 {
1885 "touch -t 202111050000.30 a b; [[ a -nt b || a -ot b ]]",
1886 "exit status 1",
1887 },
1888 {
1889 "touch -t 202111050200.00 a; touch -t 202111060100.00 b; [[ a -nt b ]]",
1890 "exit status 1",
1891 },
1892 {
1893 "touch -t 202111050000.00 a; touch -t 202111060000.00 b; [[ a -ot b ]]",
1894 "",
1895 },
1896 {
1897 ">a; [[ a -nt b ]]",
1898 "",
1899 },
1900 {
1901 ">a; [[ a -ot b ]]",
1902 "exit status 1",
1903 },
1904 {
1905 ">b; [[ a -nt b ]]",
1906 "exit status 1",
1907 },
1908 {
1909 ">b; [[ a -ot b ]]",
1910 "",
1911 },
1912 {
1913 "[[ a -ef b ]]",
1914 "exit status 1",
1915 },
1916 {
1917 ">a >b; [[ a -ef b ]]",
1918 "exit status 1",
1919 },
1920 {
1921 ">a; [[ a -ef a ]]",
1922 "",
1923 },
1924 {
1925 ">a; ln a b; [[ a -ef b ]]",
1926 "",
1927 },
1928 {
1929 ">a; ln -s a b; [[ a -ef b ]]",
1930 "",
1931 },
1932 {
1933 "[[ -z 'foo' || -n '' ]]",
1934 "exit status 1",
1935 },
1936 {
1937 "[[ -z '' && -n 'foo' ]]",
1938 "",
1939 },
1940 {
1941 "a=x b=''; [[ -v a && -v b && ! -v c ]]",
1942 "",
1943 },
1944 {
1945 "[[ abc == *b* ]]",
1946 "",
1947 },
1948 {
1949 "[[ abc != *b* ]]",
1950 "exit status 1",
1951 },
1952 {
1953 "[[ *b = '*b' ]]",
1954 "",
1955 },
1956 {
1957 "[[ ab == a. ]]",
1958 "exit status 1",
1959 },
1960 {
1961 `x='*b*'; [[ abc == $x ]]`,
1962 "",
1963 },
1964 {
1965 `x='*b*'; [[ abc == "$x" ]]`,
1966 "exit status 1",
1967 },
1968 {
1969 `[[ abc == \a\bc ]]`,
1970 "",
1971 },
1972 {
1973 "[[ abc != *b'*' ]]",
1974 "",
1975 },
1976 {
1977 "[[ a =~ b ]]",
1978 "exit status 1",
1979 },
1980 {
1981 "[[ foo =~ foo && foo =~ .* && foo =~ f.o ]]",
1982 "",
1983 },
1984 {
1985 "[[ foo =~ oo ]] && echo foo; [[ foo =~ ^oo$ ]] && echo bar || true",
1986 "foo\n",
1987 },
1988 {
1989 "[[ a =~ [ ]]",
1990 "exit status 2 #JUSTERR",
1991 },
1992 {
1993 "[[ a__b__c =~ _*(b_*) ]]; echo ${BASH_REMATCH[0]}; echo ${BASH_REMATCH[1]}",
1994 "__b__\nb__\n",
1995 },
1996 {
1997 "[[ -e a ]] && echo x; >a; [[ -e a ]] && echo y",
1998 "y\n",
1999 },
2000 {
2001 "ln -s b a; [[ -e a ]] && echo x; >b; [[ -e a ]] && echo y",
2002 "y\n",
2003 },
2004 {
2005 "[[ -f a ]] && echo x; >a; [[ -f a ]] && echo y",
2006 "y\n",
2007 },
2008 {
2009 "[[ -e a ]] && echo x; mkdir a; [[ -e a ]] && echo y",
2010 "y\n",
2011 },
2012 {
2013 "[[ -d a ]] && echo x; mkdir a; [[ -d a ]] && echo y",
2014 "y\n",
2015 },
2016 {
2017 "[[ -r a ]] && echo x; >a; [[ -r a ]] && echo y",
2018 "y\n",
2019 },
2020 {
2021 "[[ -w a ]] && echo x; >a; [[ -w a ]] && echo y",
2022 "y\n",
2023 },
2024 {
2025 "[[ -s a ]] && echo x; echo body >a; [[ -s a ]] && echo y",
2026 "y\n",
2027 },
2028 {
2029 "[[ -L a ]] && echo x; ln -s b a; [[ -L a ]] && echo y;",
2030 "y\n",
2031 },
2032 {
2033 "[[ \"multiline\ntext\" == *text* ]] && echo x; [[ \"multiline\ntext\" == *multiline* ]] && echo y",
2034 "x\ny\n",
2035 },
2036 // * should match a newline
2037 {
2038 "[[ \"multiline\ntext\" == multiline*text ]] && echo x",
2039 "x\n",
2040 },
2041 {
2042 "[[ \"multiline\ntext\" == text ]]",
2043 "exit status 1",
2044 },
2045 {
2046 `case $'a\nb' in a*b) echo match ;; esac`,
2047 "match\n",
2048 },
2049 {
2050 `a=$'a\nb'; echo "${a/a*b/sub}"`,
2051 "sub\n",
2052 },
2053 {
2054 "mkdir a; cd a; test -f b && echo x; >b; test -f b && echo y",
2055 "y\n",
2056 },
2057 {
2058 ">a; [[ -b a ]] && echo block; [[ -c a ]] && echo char; true",
2059 "",
2060 },
2061 {
2062 "[[ -e /dev/sda ]] || { echo block; exit; }; [[ -b /dev/sda ]] && echo block; [[ -c /dev/sda ]] && echo char; true",
2063 "block\n",
2064 },
2065 {
2066 "[[ -e /dev/nvme0n1 ]] || { echo block; exit; }; [[ -b /dev/nvme0n1 ]] && echo block; [[ -c /dev/nvme0n1 ]] && echo char; true",
2067 "block\n",
2068 },
2069 {
2070 "[[ -e /dev/tty ]] || { echo char; exit; }; [[ -b /dev/tty ]] && echo block; [[ -c /dev/tty ]] && echo char; true",
2071 "char\n",
2072 },
2073 {"[[ -t 1 ]]", "exit status 1"},
2074 {"[[ -t 1234 ]]", "exit status 1"},
2075 {"[[ -o wrong ]]", "exit status 1"},
2076 {"[[ -o errexit ]]", "exit status 1"},
2077 {"set -e; [[ -o errexit ]]", ""},
2078 {"[[ -o noglob ]]", "exit status 1"},
2079 {"set -f; [[ -o noglob ]]", ""},
2080 {"[[ -o allexport ]]", "exit status 1"},
2081 {"set -a; [[ -o allexport ]]", ""},
2082 {"[[ -o nounset ]]", "exit status 1"},
2083 {"set -u; [[ -o nounset ]]", ""},
2084 {"[[ -o noexec ]]", "exit status 1"},
2085 {"set -n; [[ -o noexec ]]", ""}, // actually does nothing, but oh well
2086 {"[[ -o pipefail ]]", "exit status 1"},
2087 {"set -o pipefail; [[ -o pipefail ]]", ""},
2088 // TODO: we don't implement precedence of && over ||.
2089 // {"[[ a == x && b == x || c == c ]]", ""},
2090 {"[[ (a == x && b == x) || c == c ]]", ""},
2091 {"[[ a == x && (b == x || c == c) ]]", "exit status 1"},
2092
2093 // classic test
2094 {
2095 "[",
2096 "1:1: [: missing matching ]\nexit status 2 #JUSTERR",
2097 },
2098 {
2099 "[ a",
2100 "1:1: [: missing matching ]\nexit status 2 #JUSTERR",
2101 },
2102 {
2103 "[ a b c ]",
2104 "1:1: not a valid test operator: `b`\nexit status 2 #JUSTERR",
2105 },
2106 {
2107 "[ a -a ]",
2108 "1:1: -a must be followed by an expression\nexit status 2 #JUSTERR",
2109 },
2110 {"[ a ]", ""},
2111 {"[ -n ]", ""},
2112 {"[ '-n' ]", ""},
2113 {"[ -z ]", ""},
2114 {"[ ! ]", ""},
2115 {"[ a != b ]", ""},
2116 {"[ ! a '==' a ]", "exit status 1"},
2117 {"[ a -a 0 -gt 1 ]", "exit status 1"},
2118 {"[ 0 -gt 1 -o 1 -gt 0 ]", ""},
2119 {"[ 3 -gt 4 ]", "exit status 1"},
2120 {"[ 3 -lt 4 ]", ""},
2121 {"[ ' 3' -lt '4 ' ]", ""},
2122 {
2123 "[ -e a ] && echo x; >a; [ -e a ] && echo y",
2124 "y\n",
2125 },
2126 {
2127 "test 3 -gt 4",
2128 "exit status 1",
2129 },
2130 {
2131 "test 3 -lt 4",
2132 "",
2133 },
2134 {
2135 "test 3 -lt",
2136 "1:1: -lt must be followed by a word\nexit status 2 #JUSTERR",
2137 },
2138 {
2139 "touch -t 202111050000.00 a; touch -t 202111060000.00 b; [ a -nt b ]",
2140 "exit status 1",
2141 },
2142 {
2143 "touch -t 202111050000.00 a; touch -t 202111060000.00 b; [ a -ot b ]",
2144 "",
2145 },
2146 {
2147 ">a; [ a -nt b ]",
2148 "",
2149 },
2150 {
2151 ">b; [ a -ot b ]",
2152 "",
2153 },
2154 {
2155 "[ a -nt b ]",
2156 "exit status 1",
2157 },
2158 {
2159 ">a; [ a -ef a ]",
2160 "",
2161 },
2162 {"[ 3 -eq 04 ]", "exit status 1"},
2163 {"[ 3 -eq 03 ]", ""},
2164 {"[ 3 -ne 03 ]", "exit status 1"},
2165 {"[ 3 -le 4 ]", ""},
2166 {"[ 3 -ge 4 ]", "exit status 1"},
2167 {
2168 "[ -d a ] && echo x; mkdir a; [ -d a ] && echo y",
2169 "y\n",
2170 },
2171 {
2172 "[ -r a ] && echo x; >a; [ -r a ] && echo y",
2173 "y\n",
2174 },
2175 {
2176 "[ -w a ] && echo x; >a; [ -w a ] && echo y",
2177 "y\n",
2178 },
2179 {
2180 // A directory is readable, writable, and executable.
2181 "mkdir d; [ -r d ] && echo r; [ -w d ] && echo w; [ -x d ] && echo x",
2182 "r\nw\nx\n",
2183 },
2184 {
2185 "test -? a",
2186 // TODO: this error message should refer to `-?`
2187 "1:1: not a valid test operator: `a`\n1:1: a must be followed by a word\nexit status 2 #JUSTERR",
2188 },
2189 {
2190 "[ -s a ] && echo x; echo body >a; [ -s a ] && echo y",
2191 "y\n",
2192 },
2193 {
2194 "[ -L a ] && echo x; ln -s b a; [ -L a ] && echo y;",
2195 "y\n",
2196 },
2197 {
2198 ">a; [ -b a ] && echo block; [ -c a ] && echo char; true",
2199 "",
2200 },
2201 {"[ -t 1 ]", "exit status 1"},
2202 {"[ -t 1234 ]", "exit status 1"},
2203 {"[ -o wrong ]", "exit status 1"},
2204 {"[ -o errexit ]", "exit status 1"},
2205 {"set -e; [ -o errexit ]", ""},
2206 {"a=x b=''; [ -v a -a -v b -a ! -v c ]", ""},
2207 {"[ a = a ]", ""},
2208 {"[ a != a ]", "exit status 1"},
2209 {"[ abc = ab* ]", "exit status 1"},
2210 {"[ abc != ab* ]", ""},
2211 // TODO: we don't implement precedence of -a over -o.
2212 // {"[ a = x -a b = x -o c = c ]", ""},
2213 {`[ \( a = x -a b = x \) -o c = c ]`, ""},
2214 {`[ a = x -a \( b = x -o c = c \) ]`, "exit status 1"},
2215
2216 // arithm
2217 {
2218 "echo $((1 == +1))",
2219 "1\n",
2220 },
2221 {
2222 "echo $((!0))",
2223 "1\n",
2224 },
2225 {
2226 "echo $((!3))",
2227 "0\n",
2228 },
2229 {
2230 "echo $((~0))",
2231 "-1\n",
2232 },
2233 {
2234 "echo $((~3))",
2235 "-4\n",
2236 },
2237 {
2238 "echo $((1 + 2 - 3))",
2239 "0\n",
2240 },
2241 {
2242 "echo $((-1 * 6 / 2))",
2243 "-3\n",
2244 },
2245 {
2246 "a=2; echo $(( a + $a + c ))",
2247 "4\n",
2248 },
2249 {
2250 "a=b; b=c; c=5; echo $((a % 3))",
2251 "2\n",
2252 },
2253 {
2254 "echo $((2 > 2 || 2 < 2))",
2255 "0\n",
2256 },
2257 {
2258 "echo $((2 >= 2 && 2 <= 2))",
2259 "1\n",
2260 },
2261 {
2262 "x=0; echo $((0 && (x = 1))) $x",
2263 "0 0\n",
2264 },
2265 {
2266 "x=0; echo $((1 || (x = 1))) $x",
2267 "1 0\n",
2268 },
2269 {
2270 "x=0; echo $((0 && x++)) $x $((1 || x++)) $x",
2271 "0 0 1 0\n",
2272 },
2273 {
2274 "x=0; echo $((1 && (x = 1))) $x",
2275 "1 1\n",
2276 },
2277 {
2278 "x=0; echo $((0 || (x = 2))) $x",
2279 "1 2\n",
2280 },
2281 {
2282 "echo $((0 && 1/0)) $((1 || 1/0))",
2283 "0 1\n",
2284 },
2285 {
2286 "x=0; y=0; echo $((0 && (x = 1) || (y = 2))) $x $y",
2287 "1 0 2\n",
2288 },
2289 {
2290 "x=0; echo $((1/0 && x++)); echo $x",
2291 "division by zero\n0\n #JUSTERR",
2292 },
2293 {
2294 "echo $(((1 & 2) != (1 | 2)))",
2295 "1\n",
2296 },
2297 {
2298 "echo $a; echo $((a = 3 ^ 2)); echo $a",
2299 "\n1\n1\n",
2300 },
2301 {
2302 "echo $((a += 1, a *= 2, a <<= 2, a >> 1))",
2303 "4\n",
2304 },
2305 {
2306 "echo $((a -= 10, a /= 2, a >>= 1, a << 1))",
2307 "-6\n",
2308 },
2309 {
2310 "echo $((a |= 3, a &= 1, a ^= 8, a %= 5, a))",
2311 "4\n",
2312 },
2313 {
2314 "echo $((a = 3, ++a, a--))",
2315 "4\n",
2316 },
2317 {
2318 "echo $((2 ** 3)) $((1234 ** 4567))",
2319 "8 0\n",
2320 },
2321 {
2322 "echo $((2 ** -1)); let x=2**-1",
2323 "exponent less than 0\nexponent less than 0\nexit status 1 #JUSTERR",
2324 },
2325 {
2326 "echo $((1 ? 2 : 3)) $((0 ? 2 : 3))",
2327 "2 3\n",
2328 },
2329 {
2330 "echo $((2 ? 3 : 4)) $((-1 ? 3 : 4))",
2331 "3 3\n",
2332 },
2333 {
2334 "echo $((255+1))",
2335 "256\n",
2336 },
2337 {
2338 "echo $((0xff+1))",
2339 "256\n",
2340 },
2341 {
2342 "echo $((0377+1))",
2343 "256\n",
2344 },
2345 {
2346 "echo $((10#255+1))",
2347 "256\n",
2348 },
2349 {
2350 "echo $((16#ff+1))",
2351 "256\n",
2352 },
2353 {
2354 "echo $((2#11111111+1))",
2355 "256\n",
2356 },
2357 // TODO: Enable this test once integer bit widths are
2358 // handled in a consistent manner throughout the library.
2359 //{
2360 // "echo $((16#badc0ffee+1))",
2361 // "50159747055\n",
2362 //},
2363 {
2364 "echo $((16#cafe+1))",
2365 "51967\n",
2366 },
2367 {
2368 "x=-010 y=+010 z=-0x10; echo $((x)) $((y)) $((z))",
2369 "-8 8 -16\n",
2370 },
2371 {
2372 "echo $((64#z)) $((64#Z)) $((40#A)) $((64#10)) $((36#z))",
2373 "35 61 36 64 35\n",
2374 },
2375 {
2376 "a=64#@ b=64#_ c=64#1_; echo $((a)) $((b)) $((c))",
2377 "62 63 127\n",
2378 },
2379 {
2380 "echo $((nope+1))",
2381 "1\n", // Yes, this is what bash does.
2382 },
2383 {
2384 "((1))",
2385 "",
2386 },
2387 {
2388 "((3 == 4))",
2389 "exit status 1",
2390 },
2391 {
2392 "let i=(3+4); let i++; echo $i; let i--; echo $i",
2393 "8\n7\n",
2394 },
2395 {
2396 "let 3==4",
2397 "exit status 1",
2398 },
2399 {
2400 "a=1; let a++; echo $a",
2401 "2\n",
2402 },
2403 {
2404 "a=$((1 + 2)); echo $a",
2405 "3\n",
2406 },
2407 {
2408 "x=3; echo $(($x)) $((x))",
2409 "3 3\n",
2410 },
2411 {
2412 "set -- 1; echo $(($@))",
2413 "1\n",
2414 },
2415 {
2416 "a=b b=a; echo $(($a))",
2417 "0\n #IGNORE bash prints a warning",
2418 },
2419 {
2420 "let x=3; let 3/0; ((3/0)); echo $((x/y)); let x/=0",
2421 "division by zero\ndivision by zero\ndivision by zero\ndivision by zero\nexit status 1 #JUSTERR",
2422 },
2423 {
2424 "let x=3; let 3%0; ((3%0)); echo $((x%y)); let x%=0",
2425 "division by zero\ndivision by zero\ndivision by zero\ndivision by zero\nexit status 1 #JUSTERR",
2426 },
2427 {
2428 "let x=' 3'; echo $x",
2429 "3\n",
2430 },
2431 {
2432 "x=' 3'; let x++; echo \"$x\"",
2433 "4\n",
2434 },
2435
2436 // set/shift
2437 {
2438 "echo $#; set foo bar; echo $#",
2439 "0\n2\n",
2440 },
2441 {
2442 "shift; set a b c; shift; echo $@",
2443 "b c\n",
2444 },
2445 {
2446 "shift 2; set a b c; shift 2; echo $@",
2447 "c\n",
2448 },
2449 {
2450 `echo $#; set '' ""; echo $#`,
2451 "0\n2\n",
2452 },
2453 {
2454 "set -- a b; echo $#",
2455 "2\n",
2456 },
2457 {
2458 "set +; echo $#",
2459 "0\n",
2460 },
2461 {
2462 "set + a b; echo $# $1 $2",
2463 "2 a b\n",
2464 },
2465 {
2466 "set -U",
2467 "set: invalid option: \"-U\"\nexit status 2 #JUSTERR",
2468 },
2469 {
2470 "set -e; false; echo foo",
2471 "exit status 1",
2472 },
2473 {
2474 "set -e; shouldnotexist; echo foo",
2475 "\"shouldnotexist\": executable file not found in $PATH\nexit status 127 #JUSTERR",
2476 },
2477 {
2478 "set -e; set +e; false; echo foo",
2479 "foo\n",
2480 },
2481 {
2482 "set -e; ! false; echo foo",
2483 "foo\n",
2484 },
2485 {
2486 "set -e; ! true; echo foo",
2487 "foo\n",
2488 },
2489 {
2490 "set -e; if false; then echo never; fi; echo foo",
2491 "foo\n",
2492 },
2493 {
2494 "set -e; while false; do echo never; done; echo foo",
2495 "foo\n",
2496 },
2497 {
2498 "set -e; false || true; echo foo",
2499 "foo\n",
2500 },
2501 {
2502 "set -e; false && true; echo foo",
2503 "foo\n",
2504 },
2505 {
2506 "set -e; true && false; echo foo",
2507 "exit status 1",
2508 },
2509 {
2510 "false | :",
2511 "",
2512 },
2513 {
2514 // Important that we don't print in these, as otherwise we get "broken pipe" errors.
2515 "GOSH_CMD=exit_5 $GOSH_PROG | GOSH_CMD=exit_0 $GOSH_PROG",
2516 "",
2517 },
2518 {
2519 "set -o pipefail; false | :",
2520 "exit status 1",
2521 },
2522 {
2523 "set -o pipefail; GOSH_CMD=exit_5 $GOSH_PROG | GOSH_CMD=exit_0 $GOSH_PROG",
2524 "exit status 5",
2525 },
2526 {
2527 "set -o pipefail; true | false | true | :",
2528 "exit status 1",
2529 },
2530 {
2531 "set -o pipefail; set -M 2>/dev/null | false",
2532 "exit status 1",
2533 },
2534 {
2535 "set -o pipefail; false | :; echo next",
2536 "next\n",
2537 },
2538 {
2539 "set -o pipefail; exit 0 | :; echo next",
2540 "next\n",
2541 },
2542 {
2543 "set -o pipefail; exit 1 | :; echo next",
2544 "next\n",
2545 },
2546 {
2547 "set -e -o pipefail; false | :; echo next",
2548 "exit status 1",
2549 },
2550 {
2551 "exit 0 && true; echo foo",
2552 "",
2553 },
2554 {
2555 "exit 1 && true; echo foo",
2556 "exit status 1",
2557 },
2558 {
2559 "set -f; >a.x; echo *.x;",
2560 "*.x\n",
2561 },
2562 {
2563 "set -f; set +f; >a.x; echo *.x;",
2564 "a.x\n",
2565 },
2566 {
2567 "set -a; foo=bar; $ENV_PROG | grep ^foo=",
2568 "foo=bar\n",
2569 },
2570 {
2571 "set -a; foo=(b a r); $ENV_PROG | grep ^foo=",
2572 "exit status 1",
2573 },
2574 {
2575 "foo=bar; set -a; $ENV_PROG | grep ^foo=",
2576 "exit status 1",
2577 },
2578 {
2579 "a=b; echo $a; set -u; echo $a",
2580 "b\nb\n",
2581 },
2582 {
2583 "echo $a; set -u; echo $a; echo extra",
2584 "\na: unbound variable\nexit status 1 #JUSTERR",
2585 },
2586 {
2587 "foo=bar; set -u; echo ${foo/bar/}",
2588 "\n",
2589 },
2590 {
2591 "foo=bar; set -u; echo ${foo#bar}",
2592 "\n",
2593 },
2594 {
2595 "set -u; echo ${foo/bar/}",
2596 "foo: unbound variable\nexit status 1 #JUSTERR",
2597 },
2598 {
2599 "set -u; echo ${foo#bar}",
2600 "foo: unbound variable\nexit status 1 #JUSTERR",
2601 },
2602 // TODO: detect this case as unset
2603 // {
2604 // "set -u; foo=(bar); echo $foo; echo ${foo[3]}",
2605 // "bar\nfoo: unbound variable\nexit status 1 #JUSTERR",
2606 // },
2607 {
2608 "set -u; foo=(''); echo ${foo[0]}",
2609 "\n",
2610 },
2611 {
2612 "set -u; echo ${#foo}",
2613 "foo: unbound variable\nexit status 1 #JUSTERR",
2614 },
2615 {
2616 "set -u; echo ${foo+bar}",
2617 "\n",
2618 },
2619 {
2620 "set -u; echo ${foo:+bar}",
2621 "\n",
2622 },
2623 {
2624 "set -u; echo ${foo-bar}",
2625 "bar\n",
2626 },
2627 {
2628 "set -u; echo ${foo:-bar}",
2629 "bar\n",
2630 },
2631 {
2632 "set -u; echo ${foo=bar}",
2633 "bar\n",
2634 },
2635 {
2636 "set -u; echo ${foo:=bar}",
2637 "bar\n",
2638 },
2639 {
2640 "set -u; echo ${foo?bar}",
2641 "foo: bar\nexit status 1 #JUSTERR",
2642 },
2643 {
2644 "set -u; echo ${foo:?bar}",
2645 "foo: bar\nexit status 1 #JUSTERR",
2646 },
2647 {
2648 "set -ue; set -ueo pipefail",
2649 "",
2650 },
2651 {"set -n; echo foo", ""},
2652 {"set -n; [ wrong", ""},
2653 {"set -n; set +n; echo foo", ""},
2654 {
2655 "set -o foobar",
2656 "set: invalid option: \"foobar\"\nexit status 2 #JUSTERR",
2657 },
2658 {"set -o noexec; echo foo", ""},
2659 {"set +o noexec; echo foo", "foo\n"},
2660 {"set -e; set -o | grep -E 'errexit|noexec' | wc -l | tr -d ' '", "2\n"},
2661 {"set -e; set -o | grep -E 'errexit|noexec' | grep 'on$' | wc -l | tr -d ' '", "1\n"},
2662 {
2663 "set -a; set +o",
2664 `set -o allexport
2665 set +o errexit
2666 set +o noexec
2667 set +o noglob
2668 set +o nounset
2669 set +o xtrace
2670 set +o pipefail
2671 #IGNORE`,
2672 },
2673 {`set - foobar; echo $@; set -; echo $@`, "foobar\nfoobar\n"},
2674 {
2675 "set -x; set -; echo hi",
2676 "+ set -\nhi\n",
2677 },
2678
2679 // unset
2680 {
2681 "a=1; echo $a; unset a; echo $a",
2682 "1\n\n",
2683 },
2684 {
2685 "notinpath() { echo func; }; notinpath; unset -f notinpath; notinpath",
2686 "func\n\"notinpath\": executable file not found in $PATH\nexit status 127 #JUSTERR",
2687 },
2688 {
2689 "a=1; a() { echo func; }; unset -f a; echo $a",
2690 "1\n",
2691 },
2692 {
2693 "a=1; a() { echo func; }; unset -v a; a; echo $a",
2694 "func\n\n",
2695 },
2696 {
2697 "notinpath=1; notinpath() { echo func; }; notinpath; echo $notinpath; unset notinpath; notinpath; echo $notinpath; unset notinpath; notinpath",
2698 "func\n1\nfunc\n\n\"notinpath\": executable file not found in $PATH\nexit status 127 #JUSTERR",
2699 },
2700 {
2701 "unset PATH; [[ $PATH == '' ]]",
2702 "",
2703 },
2704 {
2705 "readonly a=1; echo $a; unset a; echo $a",
2706 "1\na: readonly variable\n1\n #IGNORE bash prints a warning",
2707 },
2708 {
2709 "f() { local a=1; echo $a; unset a; echo $a; }; f",
2710 "1\n\n",
2711 },
2712 {
2713 `a=b eval 'echo $a; unset a; echo $a'`,
2714 "b\n\n",
2715 },
2716 {
2717 `$(unset INTERP_GLOBAL); echo $INTERP_GLOBAL; unset INTERP_GLOBAL; echo $INTERP_GLOBAL`,
2718 "value\n\n",
2719 },
2720 {
2721 `x=orig; f() { local x=local; unset x; x=still_local; }; f; echo $x`,
2722 "orig\n",
2723 },
2724 {
2725 `x=orig; f() { local x=local; unset x; [[ -v x ]] && echo set || echo unset; }; f`,
2726 "unset\n",
2727 },
2728 {
2729 `PS3="pick one: "; select opt in foo bar baz; do echo "Selected $opt"; break; done <<< 3`,
2730 "1) foo\n2) bar\n3) baz\npick one: Selected baz\n",
2731 },
2732 {
2733 `opts=(foo bar baz); select opt in ${opts[@]}; do echo "Selected $opt"; break; done <<< 99`,
2734 "1) foo\n2) bar\n3) baz\n#? Selected \n",
2735 },
2736 {
2737 `select opt in foo; do
2738 case $opt in
2739 foo) echo "option 1"; break;;
2740 *) echo "invalid option $REPLY"; break;;
2741 esac
2742 done <<< 2`,
2743 "1) foo\n#? invalid option 2\n",
2744 },
2745 {
2746 "select opt in a b c; do echo \"got $opt\"; if [[ $REPLY == 2 ]]; then break; fi; done <<< $'1\n2'",
2747 "1) a\n2) b\n3) c\n#? got a\n#? got b\n",
2748 },
2749 {
2750 "select opt in a b; do break; done </dev/null; echo status $?",
2751 "1) a\n2) b\n#? \nstatus 1\n",
2752 },
2753 {
2754 "select opt in a b; do echo \"got $opt\"; done <<< 2",
2755 "1) a\n2) b\n#? got b\n#? \nexit status 1",
2756 },
2757 {
2758 "select opt in a b; do break; done <<< $'\n1'",
2759 "1) a\n2) b\n#? 1) a\n2) b\n#? ",
2760 },
2761
2762 // shopt
2763 {"set -e; shopt -o | grep -E '^(errexit|noexec)' | wc -l | tr -d ' '", "2\n"},
2764 {"set -e; shopt -o | grep -E '^(errexit|noexec)' | grep 'on$' | wc -l | tr -d ' '", "1\n"},
2765 {"set -e; shopt | grep -E '^(errexit|noexec)' | wc -l | tr -d ' '", "0\n"},
2766 {"shopt -s -o noexec; echo foo", ""},
2767 {"shopt -so noexec; echo foo", ""},
2768 {"shopt -u -o noexec; echo foo", "foo\n"},
2769 {"shopt -u globstar; shopt globstar | grep 'off$' | wc -l | tr -d ' '", "1\n"},
2770 {"shopt -s globstar; shopt globstar | grep 'off$' | wc -l | tr -d ' '", "0\n"},
2771 {"shopt extglob | grep 'off' | wc -l | tr -d ' '", "1\n"},
2772 {
2773 "shopt inherit_errexit",
2774 "inherit_errexit\ton\t(\"off\" not supported)\n #JUSTERR",
2775 },
2776 {
2777 "shopt -o -s pipefail; shopt -o pipefail | grep -q 'on$'",
2778 "",
2779 },
2780 {
2781 "shopt -o -u pipefail; shopt -o pipefail | grep -q 'on$'",
2782 "exit status 1",
2783 },
2784 {
2785 "shopt pipefail",
2786 "shopt: invalid option name \"pipefail\"\nexit status 1 #JUSTERR",
2787 },
2788 {
2789 "shopt -s pipefail",
2790 "shopt: invalid option name \"pipefail\"\nexit status 1 #JUSTERR",
2791 },
2792 {
2793 "shopt -o -s extglob",
2794 "shopt: invalid option name \"extglob\"\nexit status 1 #JUSTERR",
2795 },
2796 {
2797 "shopt -s login_shell",
2798 "shopt: unsupported option \"login_shell\"\nexit status 1 #IGNORE",
2799 },
2800 {
2801 "shopt -s interactive_comments",
2802 "shopt: unsupported option \"interactive_comments\"\nexit status 1 #IGNORE",
2803 },
2804 {
2805 "shopt -s nosuchname",
2806 "shopt: invalid option name \"nosuchname\"\nexit status 1 #JUSTERR",
2807 },
2808 {
2809 "shopt -o -s nosuchname",
2810 "shopt: invalid option name \"nosuchname\"\nexit status 1 #JUSTERR",
2811 },
2812 {
2813 "touch a .b ..c; shopt -u dotglob; echo *",
2814 "a\n",
2815 },
2816 {
2817 "touch a .b ..c; shopt -s dotglob; echo *",
2818 "..c .b a\n",
2819 },
2820 {
2821 "mkdir sub .sub2; touch {sub,.sub2}/{a,.b}; shopt -s globstar; shopt -u dotglob; echo **/* | sed 's@\\\\@/@g'",
2822 "sub sub/a\n",
2823 },
2824 {
2825 "mkdir sub .sub2; touch {sub,.sub2}/{a,.b}; shopt -s globstar; shopt -s dotglob; echo **/* | sed 's@\\\\@/@g'",
2826 ".sub2 .sub2/.b .sub2/a sub sub/.b sub/a\n",
2827 },
2828 {
2829 "touch a.go b.go; echo \\*.go \\[a].go a\\* 'a'\\*",
2830 "*.go [a].go a* a*\n",
2831 },
2832 {
2833 // Beware that macOS file systems are by default case-preserving but
2834 // case-insensitive, so e.g. "touch x X" creates only one file.
2835 "touch a ab Ac Ad; shopt -u nocaseglob; echo a*",
2836 "a ab\n",
2837 },
2838 {
2839 "touch a ab Ac Ad; shopt -s nocaseglob; echo a*",
2840 "Ac Ad a ab\n",
2841 },
2842 {
2843 "touch a ab abB Ac Ad; shopt -u nocaseglob; echo *b",
2844 "ab\n",
2845 },
2846 {
2847 "touch a ab abB Ac Ad; shopt -s nocaseglob; echo *b",
2848 "ab abB\n",
2849 },
2850 {
2851 "shopt -p",
2852 "shopt: unsupported option \"-p\"\nexit status 2 #IGNORE",
2853 },
2854 {
2855 "shopt -q",
2856 "shopt: unsupported option \"-q\"\nexit status 2 #IGNORE",
2857 },
2858
2859 // IFS
2860 {`echo -n "$IFS"`, " \t\n"},
2861 {`a="x:y:z"; IFS=:; echo $a`, "x y z\n"},
2862 {`a=(x y z); IFS=-; echo ${a[*]}`, "x y z\n"},
2863 {`a=(x y z); IFS=-; echo ${a[@]}`, "x y z\n"},
2864 {`a=(x y z); IFS=-; echo "${a[*]}"`, "x-y-z\n"},
2865 {`a=(x y z); IFS=-; echo "${a[@]}"`, "x y z\n"},
2866 {`a=" x y z"; IFS=; echo $a`, " x y z\n"},
2867 {`a=(x y z); IFS=; echo "${a[*]}"`, "xyz\n"},
2868 {`a=(x y z); IFS=-; echo "${!a[@]}"`, "0 1 2\n"},
2869 {`set -- x y z; IFS=-; echo $*`, "x y z\n"},
2870 {`set -- x y z; IFS=-; echo "$*"`, "x-y-z\n"},
2871 {`set -- x y z; IFS=; echo $*`, "x y z\n"},
2872 {`set -- x y z; IFS=; echo "$*"`, "xyz\n"},
2873 {`set -- x y z; IFS=-; a=$*; echo "$a"`, "x-y-z\n"},
2874 {`set -- x y z; IFS=; a=$*; echo "$a"`, "xyz\n"},
2875 {`a=(x y z); IFS=; echo ${a[*]}; c=${a[*]}; echo "$c"`, "x y z\nxyz\n"},
2876 {`a=(x y z); IFS=-; b=${a[*]}; echo "$b"`, "x-y-z\n"},
2877 {`set -- x y; IFS=éz; a=$*; echo "$a"`, "xéy\n"},
2878 {`set -- xo yo; IFS=-; a=${*%o}; echo "$a"`, "x-y\n"},
2879 {`a=(zo wo); IFS=-; b=${a[*]^}; echo "$b"`, "Zo-Wo\n"},
2880 {`a=(x y z); IFS=-; echo "${!a[*]}"`, "0-1-2\n"},
2881 {`INTERP_Y_1=a INTERP_Y_2=b; IFS=-; echo "${!INTERP_Y_*}"`, "INTERP_Y_1-INTERP_Y_2\n"},
2882
2883 // builtin
2884 {"builtin", ""},
2885 {"builtin noexist", "exit status 1 #JUSTERR"},
2886 {"builtin echo foo", "foo\n"},
2887 {
2888 "echo() { printf 'bar\n'; }; echo foo; builtin echo foo",
2889 "bar\nfoo\n",
2890 },
2891
2892 // type
2893 {"type", ""},
2894 {"type for", "for is a shell keyword\n"},
2895 {"type echo", "echo is a shell builtin\n"},
2896 {"echo() { :; }; type echo | grep 'is a function'", "echo is a function\n"},
2897 {"type $PATH_PROG | grep -q -E ' is (/|[A-Z]:)'", ""},
2898 {"type noexist", "type: noexist: not found\nexit status 1 #JUSTERR"},
2899 {"type -o echo", "type: invalid option \"-o\"\nexit status 2 #JUSTERR"},
2900 {"PATH=/; type $PATH_PROG", "type: " + pathProg + ": not found\nexit status 1 #JUSTERR"},
2901 {"shopt -s expand_aliases; alias interp_foo='bar baz'\ntype interp_foo", "interp_foo is aliased to `bar baz'\n"},
2902 {"alias interp_foo='bar baz'\ntype interp_foo", "type: interp_foo: not found\nexit status 1 #JUSTERR"},
2903 {"type -p $PATH_PROG | grep -q -E '^(/|[A-Z]:)'", ""},
2904 {"PATH=/; type -p $PATH_PROG", "exit status 1"},
2905 // TODO: type -P should force PATH lookup even for builtins, unlike type -p.
2906 {"type -P $PATH_PROG | grep -q -E '^(/|[A-Z]:)'", ""},
2907 {"PATH=/; type -P $PATH_PROG", "exit status 1"},
2908 {"shopt -s expand_aliases; alias interp_foo='bar'; type -t interp_foo", "alias\n"},
2909 {"type -t case", "keyword\n"},
2910 {"interp_foo(){ :; }; type -t interp_foo", "function\n"},
2911 {"type -t type", "builtin\n"},
2912 {"type -t $PATH_PROG", "file\n"},
2913 {"type -t inexisting_dfgsdgfds", "exit status 1"},
2914
2915 // hash
2916 {"hash $PATH_PROG", ""},
2917
2918 // trap
2919 {"trap 'echo at_exit' EXIT; true", "at_exit\n"},
2920 {"trap 'echo on_err' ERR; false; echo FAIL", "on_err\nFAIL\n"},
2921 {"trap 'echo on_err' ERR; false || true; echo OK", "OK\n"},
2922 {"trap 'echo at_exit' EXIT; trap - EXIT; echo OK", "OK\n"},
2923 {"set -e; trap 'echo A' ERR EXIT; false; echo FAIL", "A\nA\nexit status 1"},
2924 {"trap 'foobar' UNKNOWN", "trap: UNKNOWN: invalid signal specification\nexit status 2 #JUSTERR"},
2925 // TODO: our builtin appears to not receive the piped bytes?
2926 // {"trap 'echo on_err' ERR; trap | grep -q '.*echo on_err.*'", "trap -- \"echo on_err\" ERR\n"},
2927 {"trap 'false' ERR EXIT; false", "exit status 1"},
2928 // A parse error in one trap callback must not disable later ones.
2929 {"trap '(' ERR; false; trap 'echo ok' ERR; false; :", "errortrap: error trap:1:1: `(` must be followed by a statement list\nok\n #IGNORE"},
2930 // On entry to a trap, "$?" is the status of the command which triggered it.
2931 {"trap 'echo err $?' ERR; false; echo after $?", "err 1\nafter 1\n"},
2932 {"trap 'echo exit $?' EXIT; false", "exit 1\nexit status 1"},
2933 {"trap 'echo exit $?' EXIT; true", "exit 0\n"},
2934 {"trap 'false; echo next $?' EXIT; true", "next 1\n"},
2935 {"trap 'echo err $?' ERR; trap 'echo exit $?' EXIT; false; true", "err 1\nexit 0\n"},
2936 {"false; trap 'echo exit $?' EXIT; true", "exit 0\n"},
2937
2938 // eval
2939 {"eval", ""},
2940 {"eval ''", ""},
2941 {"eval echo foo", "foo\n"},
2942 {"eval 'echo foo'", "foo\n"},
2943 {"eval 'exit 1'", "exit status 1"},
2944 {"eval '(x'", "eval: 1:1: reached EOF without matching `(` with `)`\nexit status 1 #JUSTERR"},
2945 {"set a b; eval 'echo $@'", "a b\n"},
2946 {"eval 'a=foo'; echo $a", "foo\n"},
2947 {`a=b eval "echo $a"`, "\n"},
2948 {`a=b eval 'echo $a'`, "b\n"},
2949 {`eval 'echo "\$a"'`, "$a\n"},
2950 {`a=b eval 'x=y eval "echo \$a \$x"'`, "b y\n"},
2951 {`a=b eval 'a=y eval "echo $a \$a"'`, "b y\n"},
2952 {"a=b eval '(echo $a)'", "b\n"},
2953
2954 // source
2955 {
2956 "source",
2957 "1:1: source: need filename\nexit status 2 #JUSTERR",
2958 },
2959 {
2960 "echo 'echo foo' >a; source ./a; . ./a",
2961 "foo\nfoo\n",
2962 },
2963 {
2964 "echo 'echo $@' >a; source ./a; source ./a b c; echo $@",
2965 "\nb c\n\n",
2966 },
2967 {
2968 "echo 'foo=bar' >a; source ./a; echo $foo",
2969 "bar\n",
2970 },
2971
2972 // source from PATH
2973 {
2974 "mkdir test; echo 'echo foo' >test/a; PATH=$PWD/test source a; . test/a",
2975 "foo\nfoo\n",
2976 },
2977
2978 // source with set and shift
2979 {
2980 "echo 'set -- d e f' >a; source ./a; echo $@",
2981 "d e f\n",
2982 },
2983 {
2984 "echo 'echo $@' >a; set -- b c; source ./a; echo $@",
2985 "b c\nb c\n",
2986 },
2987 {
2988 "echo 'echo $@' >a; set -- b c; source ./a d e; echo $@",
2989 "d e\nb c\n",
2990 },
2991 {
2992 "echo 'shift; echo $@' >a; set -- b c; source ./a d e; echo $@",
2993 "e\nb c\n",
2994 },
2995 {
2996 "echo 'shift' >a; set -- b c; source ./a; echo $@",
2997 "c\n",
2998 },
2999 {
3000 "echo 'shift; set -- $@' >a; set -- b c; source ./a d e; echo $@",
3001 "e\n",
3002 },
3003 {
3004 "echo 'set -- g f'>b; echo 'set -- d e f; echo $@; source ./b;' >a; source ./a; echo $@",
3005 "d e f\ng f\n",
3006 },
3007 {
3008 "echo 'set -- g f'>b; echo 'echo $@; set -- d e f; source ./b;' >a; source ./a b c; echo $@",
3009 "b c\ng f\n",
3010 },
3011 {
3012 "echo 'shift; echo $@' >b; echo 'shift; echo $@; source ./b' >a; source ./a b c d; echo $@",
3013 "c d\nd\n\n",
3014 },
3015 {
3016 "echo 'set -- b c d' >b; echo 'source ./b' >a; set -- a; source ./a; echo $@",
3017 "b c d\n",
3018 },
3019 {
3020 "echo 'echo $@' >b; echo 'set -- b c d; source ./b' >a; set -- a; source ./a; echo $@",
3021 "b c d\nb c d\n",
3022 },
3023 {
3024 "echo 'shift; echo $@' >b; echo 'shift; echo $@; source ./b c d' >a; set -- a b; source ./a; echo $@",
3025 "b\nd\nb\n",
3026 },
3027 {
3028 "echo 'set -- a b c' >b; echo 'echo $@; source ./b; echo $@' >a; source ./a; echo $@",
3029 "\na b c\na b c\n",
3030 },
3031
3032 // indexed arrays
3033 {
3034 "a=foo; echo ${a[0]} ${a[@]} ${a[x]}; echo ${a[1]}",
3035 "foo foo foo\n\n",
3036 },
3037 {
3038 "a=(); echo ${a[0]} ${a[@]} ${a[x]} ${a[1]}",
3039 "\n",
3040 },
3041 {
3042 "a=(b c); echo $a; echo ${a[0]}; echo ${a[1]}; echo ${a[x]}",
3043 "b\nb\nc\nb\n",
3044 },
3045 {
3046 "a=(b c); echo ${a[@]}; echo ${a[*]}",
3047 "b c\nb c\n",
3048 },
3049 {
3050 "a=(1 2 3); echo ${a[2-1]}; echo $((a[1+1]))",
3051 "2\n3\n",
3052 },
3053 {
3054 "a=(1 2) x=(); a+=b x+=c; echo ${a[@]}; echo ${x[@]}",
3055 "1b 2\nc\n",
3056 },
3057 {
3058 "a=(1 2) x=(); a+=(b c) x+=(d e); echo ${a[@]}; echo ${x[@]}",
3059 "1 2 b c\nd e\n",
3060 },
3061 {
3062 "a=bbb; a+=(c d); echo ${a[@]}",
3063 "bbb c d\n",
3064 },
3065 {
3066 `a=('a 1' 'b 2'); for e in ${a[@]}; do echo "$e"; done`,
3067 "a\n1\nb\n2\n",
3068 },
3069 {
3070 `a=('a 1' 'b 2'); for e in "${a[*]}"; do echo "$e"; done`,
3071 "a 1 b 2\n",
3072 },
3073 {
3074 `a=('a 1' 'b 2'); for e in "${a[@]}"; do echo "$e"; done`,
3075 "a 1\nb 2\n",
3076 },
3077 {
3078 `declare -a a; a[0]='a 1'; a[1]='b 2'; for e in "${a[@]}"; do echo "$e"; done`,
3079 "a 1\nb 2\n",
3080 },
3081 {
3082 `a=([1]=y [0]=x); echo ${a[0]}`,
3083 "x\n",
3084 },
3085 {
3086 `a=(y); a[2]=x; echo ${a[2]}`,
3087 "x\n",
3088 },
3089 {
3090 `a="y"; a[2]=x; echo ${a[2]}`,
3091 "x\n",
3092 },
3093 {
3094 `declare -a a=(x y); echo ${a[1]}`,
3095 "y\n",
3096 },
3097 {
3098 `a=b; echo "${a[@]}"`,
3099 "b\n",
3100 },
3101 {
3102 `a=(b); echo ${a[3]}`,
3103 "\n",
3104 },
3105 {
3106 `a=(b); echo ${a[-2]}`,
3107 "negative array index\n #JUSTERR",
3108 },
3109 // TODO: also test with gaps in arrays.
3110 {
3111 `a=([0]=' x ' [1]=' y '); for v in "${a[@]}"; do echo "$v"; done`,
3112 " x \n y \n",
3113 },
3114 {
3115 `a=([0]=' x ' [1]=' y '); for v in "${a[*]}"; do echo "$v"; done`,
3116 " x y \n",
3117 },
3118 {
3119 `a=([0]=' x ' [1]=' y '); for v in "${!a[@]}"; do echo "$v"; done`,
3120 "0\n1\n",
3121 },
3122 {
3123 `a=([0]=' x ' [1]=' y '); for v in "${!a[*]}"; do echo "$v"; done`,
3124 "0 1\n",
3125 },
3126
3127 // associative arrays
3128 {
3129 `a=foo; echo ${a[""]} ${a["x"]}`,
3130 "foo foo\n",
3131 },
3132 {
3133 `declare -A a=(); echo ${a[0]} ${a[@]} ${a[1]} ${a["x"]}`,
3134 "\n",
3135 },
3136 {
3137 `declare -A a=([x]=b [y]=c); echo $a; echo ${a[0]}; echo ${a["x"]}; echo ${a["_"]}`,
3138 "\n\nb\n\n",
3139 },
3140 {
3141 `declare -Ag a=([x]=y); echo ${a["x"]}`,
3142 "y\n",
3143 },
3144 {
3145 `declare -A a=([x]=b [y]=c); for e in ${a[@]}; do echo $e; done | sort`,
3146 "b\nc\n",
3147 },
3148 {
3149 `declare -A a=([y]=b [x]=c); for e in ${a[*]}; do echo $e; done | sort`,
3150 "b\nc\n",
3151 },
3152 {
3153 `declare -A a=([x]=a); a["y"]=d; a["x"]=c; for e in ${a[@]}; do echo $e; done | sort`,
3154 "c\nd\n",
3155 },
3156 {
3157 `declare -A a=([x]=a); a[y]=d; a[x]=c; for e in ${a[@]}; do echo $e; done | sort`,
3158 "c\nd\n",
3159 },
3160 {
3161 // cheating a little; bash just did a=c
3162 `a=(["x"]=b ["y"]=c); echo ${a["y"]}`,
3163 "c\n",
3164 },
3165 {
3166 `declare -A a=(['x']=b); echo ${a['x']} ${a[$'x']} ${a[$"x"]}`,
3167 "b b b\n",
3168 },
3169 {
3170 `a=(['x']=b); echo ${a['y']}`,
3171 "\n #IGNORE bash requires -A",
3172 },
3173 {
3174 `declare -A a=(['a 1']=' x ' ['b 2']=' y '); for v in "${a[@]}"; do echo "$v"; done | sort`,
3175 " x \n y \n",
3176 },
3177 {
3178 `declare -A a=(['a 1']=' x ' ['b 2']=' y '); for v in "${a[*]}"; do echo "$v"; done`,
3179 " x y \n",
3180 },
3181 {
3182 `declare -A a=(['a 1']=' x ' ['b 2']=' y '); for v in "${!a[@]}"; do echo "$v"; done | sort`,
3183 "a 1\nb 2\n",
3184 },
3185 {
3186 `declare -A a=(['a 1']=' x ' ['b 2']=' y '); for v in "${!a[*]}"; do echo "$v"; done`,
3187 "a 1 b 2\n",
3188 },
3189 {
3190 `declare -A a; a[a]=x; a[b]=y; for v in "${!a[@]}"; do echo "$v"; done | sort`,
3191 "a\nb\n",
3192 },
3193 {
3194 `declare -A a; a[a]=x; a[b]=y; declare -A a; for v in "${!a[@]}"; do echo "$v"; done | sort`,
3195 "a\nb\n",
3196 },
3197 // weird assignments
3198 {"a=b; a=(c d); echo ${a[@]}", "c d\n"},
3199 {"a=(b c); a=d; echo ${a[@]}", "d c\n"},
3200 {"declare -A a=([x]=b [y]=c); a=d; for e in ${a[@]}; do echo $e; done | sort", "b\nc\nd\n"},
3201 {"i=3; a=b; a[i]=x; echo ${a[@]}", "b x\n"},
3202 {"i=3; declare a=(b); a[i]=x; echo ${!a[@]}", "0 3\n"},
3203 {`a=(x "" y); echo ${!a[@]}; echo "${!a[@]}"`, "0 1 2\n0 1 2\n"},
3204 {"a=(0 1 2 3 4 5 6 7 8 9 10); echo ${!a[@]}", "0 1 2 3 4 5 6 7 8 9 10\n"},
3205 {"i=3; declare -A a=(['x']=b); a[i]=x; for e in ${!a[@]}; do echo $e; done | sort", "i\nx\n"},
3206
3207 // sparse indexed arrays
3208 {"a[5]=x; echo ${#a[@]} ${a[@]} ${!a[@]}", "1 x 5\n"},
3209 {"a=([5]=x [2]=y); echo ${!a[@]}; echo ${a[@]}", "2 5\ny x\n"},
3210 {"a=([5]=x y z); echo ${!a[@]}", "5 6 7\n"},
3211 {"a[5]=x; a[2]=y; declare -p a", "declare -a a=([2]=\"y\" [5]=\"x\")\n"},
3212 {"a[5]=x; echo ${a[0]-unset} ${a[5]}; echo \"${a[@]}\"", "unset x\nx\n"},
3213 {"a=(x y z); unset 'a[1]'; echo ${#a[@]} ${!a[@]} ${a[@]}", "2 0 2 x z\n"},
3214 {"a=(x y z); unset 'a[2]'; echo ${#a[@]} ${!a[@]} ${a[@]}", "2 0 1 x y\n"},
3215 {"a=(x y z); unset 'a[1]'; a+=(w); echo ${!a[@]}", "0 2 3\n"},
3216 {"a=(x y z); unset 'a[@]'; echo ${#a[@]}", "0\n"},
3217 {"a=(w x y z); i=2; unset \"a[i+1]\"; echo ${!a[@]}", "0 1 2\n"},
3218 {"declare -A a=([x]=1 [y]=2); unset 'a[x]'; echo ${!a[@]}", "y\n"},
3219 {"a=(1 2 3); a[-1]=x; echo ${a[@]}", "1 2 x\n"},
3220 {"a=(x); a+=([5]=z w); echo ${!a[@]}; echo ${a[@]}", "0 5 6\nx z w\n"},
3221 {"a=s; a+=([0]=x); echo ${a[@]}", "x\n"},
3222 {"a=([5]=x); a+=s; echo ${!a[@]}; echo ${a[@]}", "0 5\ns x\n"},
3223 {"a=([1]=one [5]=five [10]=ten); echo ${a[@]:2:2}; echo ${a[@]:5}; echo ${a[@]: -1}", "five ten\nfive ten\nten\n"},
3224 {"a=([2]=x [5]=y); echo \"${a[@]::1}\" \"${a[@]:0}\"", "x x y\n"},
3225 {"a=([2]=x [5]=y); echo $a ${a[0]-unset}", "unset\n"},
3226 {"a=([0]=x [5]=y); echo $a", "x\n"},
3227 {"a=([5]=x); echo ${a+set} ${a-unset}", "unset\n"},
3228 {"a=(x y); : \"${a[5]=z}\"; declare -p a", "declare -a a=([0]=\"x\" [1]=\"y\" [5]=\"z\")\n"},
3229 {"s=x; : \"${s[1]=z}\"; declare -p s", "declare -a s=([0]=\"x\" [1]=\"z\")\n"},
3230 {"declare -A m=([k]=v); : \"${m[j]=z}\"; echo ${m[j]} ${m[k]}", "z v\n"},
3231 {"a=([5]=b [-1]=c d); declare -p a", "declare -a a=([5]=\"c\" [6]=\"d\")\n"},
3232 {"a=(1 2 3); echo ${a[-1]} ${a[-3]}", "3 1\n"},
3233 {"a=(x); unset 'a[]'; echo $?; declare -p a", "0\ndeclare -a a=([0]=\"x\")\n"},
3234 {"s=x; unset 's[0]'; echo ${s-unset}", "unset\n"},
3235 {"s=x; unset 's[5]'; echo $s", "unset: s: not an array variable\nx\n #JUSTERR"},
3236 {"a=([5]=x); (a[2]=y; echo ${!a[@]}); echo ${!a[@]}", "2 5\n5\n"},
3237 {"a=([1]=y [0]=x); declare -p a", "declare -a a=([0]=\"x\" [1]=\"y\")\n"},
3238 {"declare -n r=a; a=(1 2 3); unset 'r[1]'; echo ${!a[@]}", "0 2\n"},
3239
3240 // declare
3241 {"declare -B foo", "declare: invalid option \"-B\"\nexit status 2 #JUSTERR"},
3242 {"a=b; declare a; echo $a; declare a=; echo $a", "b\n\n"},
3243 {"a=b; declare a; echo $a", "b\n"},
3244 {
3245 "declare a=b c=(1 2); echo $a; echo ${c[@]}",
3246 "b\n1 2\n",
3247 },
3248 {"a=x; declare $a; echo $a $x", "x\n"},
3249 {"a=x=y; declare $a; echo $a $x", "x=y y\n"},
3250 {"a='x=(y)'; declare $a; echo $a $x", "x=(y) (y)\n"},
3251 {"a='x=b y=c'; declare $a; echo $x $y", "b c\n"},
3252 {"declare =bar", "declare: invalid name \"\"\nexit status 1 #JUSTERR"},
3253 {"declare $unset=$unset", "declare: invalid name \"\"\nexit status 1 #JUSTERR"},
3254
3255 // export
3256 {"declare foo=bar; $ENV_PROG | grep '^foo='", "exit status 1"},
3257 {"declare -x foo=bar; $ENV_PROG | grep '^foo='", "foo=bar\n"},
3258 {"export foo=bar; $ENV_PROG | grep '^foo='", "foo=bar\n"},
3259 {"foo=bar; export foo; $ENV_PROG | grep '^foo='", "foo=bar\n"},
3260 {"export foo=bar; foo=baz; $ENV_PROG | grep '^foo='", "foo=baz\n"},
3261 {"export foo=bar; readonly foo=baz; $ENV_PROG | grep '^foo='", "foo=baz\n"},
3262 {"export foo=(1 2); $ENV_PROG | grep '^foo='", "exit status 1"},
3263 {"declare -A foo=([a]=b); export foo; $ENV_PROG | grep '^foo='", "exit status 1"},
3264 {"export foo=(b c); foo=x; $ENV_PROG | grep '^foo='", "exit status 1"},
3265 {"foo() { bar=foo; export bar; }; foo; $ENV_PROG | grep ^bar=", "bar=foo\n"},
3266 {"foo() { export bar; }; bar=foo; foo; $ENV_PROG | grep ^bar=", "bar=foo\n"},
3267 {"foo() { export bar; }; foo; bar=foo; $ENV_PROG | grep ^bar=", "bar=foo\n"},
3268 {"foo() { export bar=foo; }; foo; readonly bar; $ENV_PROG | grep ^bar=", "bar=foo\n"},
3269
3270 // local
3271 {
3272 "local a=b",
3273 "local: can only be used in a function\nexit status 1 #JUSTERR",
3274 },
3275 {
3276 "local a=b 2>/dev/null; echo $a",
3277 "\n",
3278 },
3279 {
3280 "{ local a=b; }",
3281 "local: can only be used in a function\nexit status 1 #JUSTERR",
3282 },
3283 {
3284 "echo 'local a=b' >a; source ./a",
3285 "local: can only be used in a function\nexit status 1 #JUSTERR",
3286 },
3287 {
3288 "echo 'local a=b' >a; f() { source ./a; }; f; echo $a",
3289 "\n",
3290 },
3291 {
3292 "f() { local a=b; }; f; echo $a",
3293 "\n",
3294 },
3295 {
3296 "a=x; f() { local a=b; }; f; echo $a",
3297 "x\n",
3298 },
3299 {
3300 "a=x; f() { echo $a; local a=b; echo $a; }; f",
3301 "x\nb\n",
3302 },
3303 {
3304 "f1() { local a=b; }; f2() { f1; echo $a; }; f2",
3305 "\n",
3306 },
3307 {
3308 "f() { a=1; declare b=2; export c=3; readonly d=4; declare -g e=5; }; f; echo $a $b $c $d $e",
3309 "1 3 4 5\n",
3310 },
3311 {
3312 `f() { local x; [[ -v x ]] && echo set || echo unset; }; f`,
3313 "unset\n",
3314 },
3315 {
3316 `f() { local x=; [[ -v x ]] && echo set || echo unset; }; f`,
3317 "set\n",
3318 },
3319 {
3320 `export x=before; f() { local x; export x=after; $ENV_PROG | grep '^x='; }; f; echo $x`,
3321 "x=after\nbefore\n",
3322 },
3323 {
3324 "getx() { echo $X; }; f() { local X=Y; getx; echo $X; }; f",
3325 "Y\nY\n",
3326 },
3327 {
3328 "setx() { X=Y; }; f() { local X; setx; echo $X; }; f",
3329 "Y\n",
3330 },
3331 {
3332 "setx() { local X=Y; }; f() { local X; setx; echo $X; }; f",
3333 "\n",
3334 },
3335 {
3336 "setx() { declare X=Y; }; f() { local X; setx; echo $X; }; f",
3337 "\n",
3338 },
3339 {
3340 "setx() { X=Y :; }; f() { local X; setx; echo $X; }; f",
3341 "\n",
3342 },
3343
3344 // unset global from inside function
3345 {"f() { unset foo; echo $foo; }; foo=bar; f", "\n"},
3346 {"f() { unset foo; }; foo=bar; f; echo $foo", "\n"},
3347
3348 // name references
3349 {"declare -n foo=bar; bar=etc; [[ -R foo ]]", ""},
3350 {"declare -n foo=bar; bar=etc; [ -R foo ]", ""},
3351 {"nameref foo=bar; bar=etc; [[ -R foo ]]", " #IGNORE"},
3352 {"declare foo=bar; bar=etc; [[ -R foo ]]", "exit status 1"},
3353 {
3354 "declare -n foo=bar; bar=etc; echo $foo; bar=zzz; echo $foo",
3355 "etc\nzzz\n",
3356 },
3357 {
3358 "declare -n foo=bar; bar=(x y); echo ${foo[1]}; bar=(a b); echo ${foo[1]}",
3359 "y\nb\n",
3360 },
3361 {
3362 "declare -n foo=bar; bar=etc; echo $foo; unset bar; echo $foo",
3363 "etc\n\n",
3364 },
3365 {
3366 "declare -n a1=a2 a2=a3 a3=a4; a4=x; echo $a1 $a3",
3367 "x x\n",
3368 },
3369 {
3370 "declare -n foo=bar bar=foo; echo $foo",
3371 "\n #IGNORE",
3372 },
3373 {
3374 "declare -n foo=bar; echo $foo",
3375 "\n",
3376 },
3377 {
3378 "declare -n foo=bar; echo ${!foo}",
3379 "bar\n",
3380 },
3381 {
3382 "declare -n foo=bar; bar=etc; echo $foo; echo ${!foo}",
3383 "etc\nbar\n",
3384 },
3385 {
3386 "declare -n foo=bar; bar=etc; foo=value; echo $foo; echo $bar",
3387 "value\nvalue\n",
3388 },
3389 {
3390 "declare -n foo=bar; foo=value; echo $foo; echo $bar",
3391 "value\nvalue\n",
3392 },
3393 {
3394 "declare -n foo=bar; declare foo=value; echo $foo; echo $bar",
3395 "value\nvalue\n",
3396 },
3397 {
3398 "declare -n foo=bar bar=baz; foo=value; echo $foo; echo $bar; echo $baz",
3399 "value\nvalue\nvalue\n",
3400 },
3401 {
3402 "declare -n foo=bar; set -u; echo ${foo}",
3403 "foo: unbound variable\nexit status 1 #JUSTERR",
3404 },
3405 {
3406 "declare -n foo=bar; set -u; echo ${foo:=value}; echo $foo; echo $bar",
3407 "value\nvalue\nvalue\n",
3408 },
3409 {
3410 "declare -n foo=bar; foo=value $ENV_PROG | grep '^bar='",
3411 "bar=value\n",
3412 },
3413 {
3414 "echo ${!@}-${!*}; set -- foo; echo ${!@}-${!*}-${!1}; foo=value; echo ${!@}-${!*}-${!1}",
3415 "-\n--\nvalue-value-value\n",
3416 },
3417 {
3418 "declare -n ref=arr; ref+=(x y); echo ${ref[@]} ${arr[@]}",
3419 "x y x y\n",
3420 },
3421
3422 // read-only vars
3423 {"declare -r foo=bar; echo $foo", "bar\n"},
3424 {"readonly foo=bar; echo $foo", "bar\n"},
3425 {"readonly foo=bar; export foo; echo $foo", "bar\n"},
3426 {"readonly foo=bar; readonly bar=foo; export foo bar; echo $bar", "foo\n"},
3427 {
3428 "a=b; a=c; echo $a; readonly a; a=d",
3429 "c\na: readonly variable\nexit status 1 #JUSTERR",
3430 },
3431 {
3432 "declare -r foo=bar; foo=etc",
3433 "foo: readonly variable\nexit status 1 #JUSTERR",
3434 },
3435 {
3436 "declare -r foo=bar; export foo=",
3437 "foo: readonly variable\nexit status 1 #JUSTERR",
3438 },
3439 {
3440 "readonly foo=bar; foo=etc",
3441 "foo: readonly variable\nexit status 1 #JUSTERR",
3442 },
3443 {
3444 "foo() { bar=foo; readonly bar; }; foo; bar=bar",
3445 "bar: readonly variable\nexit status 1 #JUSTERR",
3446 },
3447 {
3448 "foo() { readonly bar; }; foo; bar=foo",
3449 "bar: readonly variable\nexit status 1 #JUSTERR",
3450 },
3451 {
3452 "foo() { readonly bar=foo; }; foo; export bar; $ENV_PROG | grep '^bar='",
3453 "bar=foo\n",
3454 },
3455
3456 // multiple var modes at once
3457 {
3458 "declare -r -x foo=bar; $ENV_PROG | grep '^foo='",
3459 "foo=bar\n",
3460 },
3461 {
3462 "declare -r -x foo=bar; foo=x",
3463 "foo: readonly variable\nexit status 1 #JUSTERR",
3464 },
3465
3466 // globbing
3467 {"echo .", ".\n"},
3468 {"echo ..", "..\n"},
3469 {"echo ./.", "./.\n"},
3470 {
3471 ">a.x >b.x >c.x; echo *.x; rm a.x b.x c.x",
3472 "a.x b.x c.x\n",
3473 },
3474 {
3475 `>a.x; echo '*.x' "*.x"; rm a.x`,
3476 "*.x *.x\n",
3477 },
3478 {
3479 `>a.x >b.y; echo *'.'x; rm a.x`,
3480 "a.x\n",
3481 },
3482 {
3483 `>a.x; echo *'.x' "a."* '*'.x; rm a.x`,
3484 "a.x a.x *.x\n",
3485 },
3486 {
3487 "echo *.x; echo foo *.y bar",
3488 "*.x\nfoo *.y bar\n",
3489 },
3490 {
3491 `>a.x >b.x >c.x; a=*.x; echo $a; echo "$a"`,
3492 "a.x b.x c.x\n*.x\n",
3493 },
3494 {
3495 `>a.x >b.x >c.x; a=(*.x); echo "${a[@]}"; echo ${a[1]}`,
3496 "a.x b.x c.x\nb.x\n",
3497 },
3498 {
3499 "mkdir a; >a/b.x; echo */*.x | sed 's@\\\\@/@g'; cd a; echo *.x",
3500 "a/b.x\nb.x\n",
3501 },
3502 {
3503 "mkdir -p a/b/c; echo a/* | sed 's@\\\\@/@g'",
3504 "a/b\n",
3505 },
3506 {
3507 ">.hidden >a; echo *; echo .h*; rm .hidden a",
3508 "a\n.hidden\n",
3509 },
3510 {
3511 `mkdir d; >d/.hidden >d/a; set -- "$(echo d/*)" "$(echo d/.h*)"; echo ${#1} ${#2}; rm -r d`,
3512 "3 9\n",
3513 },
3514 {
3515 "mkdir -p a/b/c; echo a/** | sed 's@\\\\@/@g'",
3516 "a/b\n",
3517 },
3518 {
3519 "shopt -s globstar; mkdir -p a/b/c; echo a/** | sed 's@\\\\@/@g'",
3520 "a/ a/b a/b/c\n",
3521 },
3522 {
3523 "shopt -s globstar; mkdir -p a/b/c; echo **/c | sed 's@\\\\@/@g'",
3524 "a/b/c\n",
3525 },
3526 {
3527 "shopt -s globstar; mkdir -p a/b; touch c; echo ** | sed 's@\\\\@/@g'",
3528 "a a/b c\n",
3529 },
3530 {
3531 "shopt -s globstar; mkdir -p a/b; touch c; echo **/ | sed 's@\\\\@/@g'",
3532 "a/ a/b/\n",
3533 },
3534 {
3535 "shopt -s globstar; mkdir -p a/b/c a/d; echo ** | sed 's@\\\\@/@g'",
3536 "a a/b a/b/c a/d\n",
3537 },
3538 {
3539 "shopt -s globstar; mkdir -p a.x a/b.x a/b/c.x; echo **.x ./**.x | sed 's@\\\\@/@g'",
3540 "a.x ./a.x\n",
3541 },
3542 {
3543 "shopt -s globstar; mkdir -p a/b; touch a/b/c; echo **/* | sed 's@\\\\@/@g'",
3544 "a a/b a/b/c\n",
3545 },
3546 {
3547 "shopt -s globstar; mkdir -p b; touch x2 a b/c d x1; echo **/* | sed 's@\\\\@/@g'",
3548 "a b b/c d x1 x2\n",
3549 },
3550 {
3551 "mkdir foo; touch foo/bar; echo */bar */bar/ | sed 's@\\\\@/@g'",
3552 "foo/bar */bar/\n",
3553 },
3554 {
3555 "shopt -s nullglob; touch existing-1; echo missing-* existing-*",
3556 "existing-1\n",
3557 },
3558 {
3559 "touch ŀfoo; echo ŀ*",
3560 "ŀfoo\n",
3561 },
3562
3563 // Extended globbing via the extglob option.
3564 // Note how extglob affects Bash's own line-by-line parsing, so we set the option before a newline.
3565 {
3566 "shopt -s extglob\necho invalid-?([)",
3567 "invalid-?([)\n",
3568 },
3569 {
3570 "touch az a1z a12z a123z; echo a?([0-9])z",
3571 "extended globbing operator used without the \"extglob\" option set\n #JUSTERR",
3572 },
3573 {
3574 "shopt -s extglob\ntouch az a1z a12z a123z; echo a?([0-9])z",
3575 "a1z az\n",
3576 },
3577 {
3578 "shopt -s extglob\ntouch az a1z a12z a123z; echo a*([0-9])z",
3579 "a123z a12z a1z az\n",
3580 },
3581 {
3582 "shopt -s extglob\ntouch az a1z a12z a123z; echo a+([0-9])z",
3583 "a123z a12z a1z\n",
3584 },
3585 {
3586 "shopt -s extglob\ntouch az a1z a12z a123z; echo a@([0-9])z",
3587 "a1z\n",
3588 },
3589 {
3590 "shopt -s extglob\ntouch a{1..9}0z; echo a+(0|[1-2]|8)z",
3591 "a10z a20z a80z\n",
3592 },
3593 {
3594 "shopt -s extglob\ntouch az a1z a12z a123z; echo a!([0-9])z",
3595 "a123z a12z az\n",
3596 },
3597 // !(pattern) extglob negation in case and [[ ]] matching
3598 {
3599 "shopt -s extglob\ncase \"bar\" in !(foo)) echo match;; esac",
3600 "match\n",
3601 },
3602 {
3603 "shopt -s extglob\ncase \"foo\" in !(foo)) echo match;; esac",
3604 "",
3605 },
3606 {
3607 "shopt -s extglob\ncase \"\" in !(foo)) echo match;; esac",
3608 "match\n",
3609 },
3610 {
3611 "shopt -s extglob\ncase \"baz\" in !(foo|bar)) echo match;; esac",
3612 "match\n",
3613 },
3614 {
3615 "shopt -s extglob\ncase \"file.tar.gz\" in !(*.sig)) echo match;; esac",
3616 "match\n",
3617 },
3618 {
3619 "shopt -s extglob\ncase \"file.sig\" in !(*.sig)) echo match;; esac",
3620 "",
3621 },
3622 {
3623 "shopt -s extglob\ncase \"foo_xxx_baz\" in foo_!(bar)_baz) echo match;; esac",
3624 "match\n",
3625 },
3626 {
3627 "shopt -s extglob\ncase \"foo_bar_baz\" in foo_!(bar)_baz) echo match;; esac",
3628 "",
3629 },
3630 {
3631 "shopt -s extglob\n[[ \"bar\" == !(foo) ]] && echo match",
3632 "match\n",
3633 },
3634 // Unsupported: multiple groups, glob prefix, or glob suffix.
3635 {
3636 "shopt -s extglob\ncase \"xabab\" in *a!(b)) echo match;; esac",
3637 "extglob !(...) is only supported with a fixed prefix and suffix\n #IGNORE glob prefix not supported",
3638 },
3639 {
3640 "shopt -s extglob\ncase \"baz\" in !(foo)!(bar)) echo match;; esac",
3641 "multiple extglob !(...) groups are not supported yet\n #IGNORE multiple extglob negation groups not supported",
3642 },
3643 {
3644 "shopt -s extglob\ncase \".bar\" in .*!(foo)) echo match;; esac",
3645 "extglob !(...) is only supported with a fixed prefix and suffix\n #IGNORE glob prefix not supported",
3646 },
3647 {
3648 "shopt -s extglob\ncase \".foo\" in .*!(foo)) echo match;; esac",
3649 "extglob !(...) is only supported with a fixed prefix and suffix\n #IGNORE glob prefix not supported",
3650 },
3651 {
3652 "shopt -s extglob\ncase \"bar\" in .*!(foo)) echo match;; esac",
3653 "extglob !(...) is only supported with a fixed prefix and suffix\n #IGNORE glob prefix not supported",
3654 },
3655 {
3656 // Extended pattern matching is always available outside of pathname expansions (globbing).
3657 "[[ a123z == a@([0-9])z ]]; echo $?; [[ a123z == a+([0-9])z ]]; echo $?",
3658 "1\n0\n",
3659 },
3660 {
3661 // An unclosed extended pattern group is literal text, like in Bash.
3662 "p='@(a'; case '@(a' in $p) echo lit;; esac; [[ a == $p ]]; echo $?",
3663 "lit\n1\n",
3664 },
3665 // Ensure that setting nullglob does not return invalid globs as null
3666 // strings.
3667 {
3668 "shopt -s nullglob; [ -n butter ] && echo bubbles",
3669 "bubbles\n",
3670 },
3671 {
3672 "cat <<EOF\n{foo,bar}\nEOF",
3673 "{foo,bar}\n",
3674 },
3675 {
3676 "cat <<EOF\n*.go\nEOF",
3677 "*.go\n",
3678 },
3679 {
3680 "mkdir -p a/b a/c; echo ./a/* | sed 's@\\\\@/@g'",
3681 "./a/b ./a/c\n",
3682 },
3683 {
3684 "mkdir -p a/b a/c d; cd d; echo ../a/* | sed 's@\\\\@/@g'",
3685 "../a/b ../a/c\n",
3686 },
3687 {
3688 "mkdir x-d1 x-d2; >x-f; echo x-*/ | sed 's@\\\\@/@g'",
3689 "x-d1/ x-d2/\n",
3690 },
3691 {
3692 "mkdir x-d1 x-d2; >x-f; echo ././x-*/// | sed 's@\\\\@/@g'",
3693 "././x-d1/ ././x-d2/\n",
3694 },
3695 {
3696 "mkdir -p x-d1/a x-d2/b; >x-f; echo x-*/* | sed 's@\\\\@/@g'",
3697 "x-d1/a x-d2/b\n",
3698 },
3699 {
3700 "mkdir -p foo/bar; ln -s foo sym; echo sy*/; echo sym/b*",
3701 "sym/\nsym/bar\n",
3702 },
3703 {
3704 ">foo; ln -s foo sym; echo sy*; echo sy*/",
3705 "sym\nsy*/\n",
3706 },
3707 {
3708 "mkdir x-d; >x-f; test -d $PWD/x-*/",
3709 "",
3710 },
3711 {
3712 "mkdir dir; >dir/x-f; ln -s dir sym; cd sym; test -f $PWD/x-*",
3713 "",
3714 },
3715
3716 // brace expansion; there are also some tests in the expand package
3717 {"echo a}b", "a}b\n"},
3718 {"echo {a,b{c,d}", "{a,bc {a,bd\n"},
3719 {"echo a{b}", "a{b}\n"},
3720 {"echo a{à,世界}", "aà a世界\n"},
3721 {"echo a{b,c}d{e,f}g", "abdeg abdfg acdeg acdfg\n"},
3722 {"echo a{b{x,y},c}d", "abxd abyd acd\n"},
3723 {"echo a{1..", "a{1..\n"},
3724 {
3725 "echo {00..2}; echo {01..10}; echo {1..10..-2}; echo {10..1..2}; echo {-03..3}",
3726 "00 01 02\n01 02 03 04 05 06 07 08 09 10\n1 3 5 7 9\n10 8 6 4 2\n-03 -02 -01 000 001 002 003\n",
3727 },
3728 {"echo a{1..2}b{4..5}c", "a1b4c a1b5c a2b4c a2b5c\n"},
3729 {"echo a{c..f}", "ac ad ae af\n"},
3730 {"echo a{4..1..1}", "a4 a3 a2 a1\n"},
3731 {"b=c; echo ${b}a{4..1..1}", "ca4 ca3 ca2 ca1\n"},
3732 {"b=c; echo a{1,2}$b", "a1c a2c\n"},
3733 {"echo a{1,2}'bc'", "a1bc a2bc\n"},
3734 {`echo a\{1,2}b`, "a{1,2}b\n"},
3735 {`echo a{1,2\`, "a{1,2\\\n"},
3736 {`echo a{1,2\}b`, "a{1,2}b\n"},
3737 {`echo a{1\,2,3}b`, "a1,2b a3b\n"},
3738 {`echo a{1\}2,3}b`, "a1}2b a3b\n"},
3739 {`echo a{1\..2}b`, "a{1..2}b\n"},
3740 {`echo \{\{iriname\}\}`, "{{iriname}}\n"},
3741 {
3742 "echo {1..100000}",
3743 "brace expansion would exceed 16384 elements\n #IGNORE bash has no defensive limit below MaxInt",
3744 },
3745 {
3746 "echo a{0..9999999999}b",
3747 "brace expansion would exceed 16384 elements\n #IGNORE bash limits sequence bounds to a C long, so 32-bit bash leaves this literal",
3748 },
3749
3750 // brace expansion in declarations
3751 {"declare {A,B}_VAR=1; echo $A_VAR $B_VAR", "1 1\n"},
3752 {"declare {x,y}=val; echo $x $y", "val val\n"},
3753 {"declare -x RUN_{VERY_,}EXPENSIVE_TESTS=yes; echo $RUN_EXPENSIVE_TESTS", "yes\n"},
3754 {"declare {A,B}_VAR; A_VAR=1; B_VAR=2; echo $A_VAR $B_VAR", "1 2\n"},
3755 {"declare {foo=x,bar=y}; echo $foo $bar", "x y\n"},
3756 {`declare foo{bar=baz`, "declare: invalid name \"foo{bar\"\nexit status 1 #JUSTERR"},
3757 {"{a,b}=value", "\"a=value\": executable file not found in $PATH\nexit status 127 #JUSTERR"},
3758
3759 // tilde expansion
3760 {
3761 "[[ '~/foo' == ~/foo ]] || [[ ~/foo == '~/foo' ]]",
3762 "exit status 1",
3763 },
3764 {
3765 "case '~/foo' in ~/foo) echo match ;; esac",
3766 "",
3767 },
3768 {
3769 "a=~/foo; [[ $a == '~/foo' ]]",
3770 "exit status 1",
3771 },
3772 {
3773 `a=$(echo "~/foo"); [[ $a == '~/foo' ]]`,
3774 "",
3775 },
3776 {
3777 `HOME=/foo; rel=/bar; echo ~/bar ~/'bar' ~/"bar" ~/$rel ~/"$rel"`,
3778 "/foo/bar /foo/bar /foo/bar /foo//bar /foo//bar\n",
3779 },
3780 {
3781 `HOME=/foo; rel=/bar; echo ~'/bar' ~"/bar" ~$rel ~"/$rel"`,
3782 "~/bar ~/bar ~/bar ~//bar\n",
3783 },
3784 {
3785 `HOME=/foo; echo ~ ~/ ~/'' ~'' ~""`,
3786 "/foo /foo/ /foo/ ~ ~\n",
3787 },
3788
3789 // /dev/null
3790 {"echo foo >/dev/null", ""},
3791 {"cat </dev/null", ""},
3792
3793 // time - real would be slow and flaky; see TestElapsedString
3794 {"{ time; } |& wc | tr -s ' '", " 4 6 42\n"},
3795 {"{ time echo -n; } |& wc | tr -s ' '", " 4 6 42\n"},
3796 {"{ time -p; } |& wc | tr -s ' '", " 3 6 29\n"},
3797 {"{ time -p echo -n; } |& wc | tr -s ' '", " 3 6 29\n"},
3798
3799 // exec
3800 {"exec", ""},
3801 {
3802 "exec builtin echo foo",
3803 "\"builtin\": executable file not found in $PATH\nexit status 127 #JUSTERR",
3804 },
3805 {
3806 "exec $GOSH_PROG 'echo foo'; echo bar",
3807 "foo\n",
3808 },
3809
3810 // read
3811 {
3812 "read </dev/null",
3813 "exit status 1",
3814 },
3815 {
3816 "read 1</dev/null",
3817 "exit status 1",
3818 },
3819 {
3820 "read -X",
3821 "read: invalid option \"-X\"\nexit status 2 #JUSTERR",
3822 },
3823 {
3824 "read -rX",
3825 "read: invalid option \"-X\"\nexit status 2 #JUSTERR",
3826 },
3827 {
3828 "read 0ab",
3829 "read: invalid identifier \"0ab\"\nexit status 2 #JUSTERR",
3830 },
3831 {
3832 "read <<< foo; echo $REPLY",
3833 "foo\n",
3834 },
3835 {
3836 "read <<<' a b c '; echo \"$REPLY\"",
3837 " a b c \n",
3838 },
3839 {
3840 "read <<< 'y\nn\n'; echo $REPLY",
3841 "y\n",
3842 },
3843 {
3844 "read a_0 <<< foo; echo $a_0",
3845 "foo\n",
3846 },
3847 {
3848 "read a b <<< 'foo bar baz '; echo \"$a\"; echo \"$b\"",
3849 "foo\nbar baz\n",
3850 },
3851 {
3852 "while read a; do echo $a; done <<< 'a\nb\nc'",
3853 "a\nb\nc\n",
3854 },
3855 {
3856 "while read a b; do echo -e \"$a\n$b\"; done <<< '1 2\n3'",
3857 "1\n2\n3\n\n",
3858 },
3859 {
3860 `read a <<< '\\'; echo "$a"`,
3861 "\\\n",
3862 },
3863 {
3864 `read a <<< '\a\b\c'; echo "$a"`,
3865 "abc\n",
3866 },
3867 {
3868 "read -r a b <<< '1\\\t2'; echo $a; echo $b;",
3869 "1\\\n2\n",
3870 },
3871 {
3872 "echo line\\\ncontinuation | while read a; do echo $a; done",
3873 "linecontinuation\n",
3874 },
3875 {
3876 "read x <<< $'foo\\\\\nbar'; echo \"$x\"",
3877 "foobar\n",
3878 },
3879 {
3880 "read x <<< $'a\\\\\nb\\\\\nc'; echo \"$x\"",
3881 "abc\n",
3882 },
3883 {
3884 "read -r x <<< $'foo\\\\\nbar'; echo \"$x\"",
3885 "foo\\\n",
3886 },
3887 {
3888 "while read a; do echo $a; GOSH_CMD=print_ok $GOSH_PROG; done <<< 'a\nb\nc'",
3889 "a\nexec ok\nb\nexec ok\nc\nexec ok\n",
3890 },
3891 {
3892 "while read a; do echo $a; GOSH_CMD=print_ok $GOSH_PROG; done <<EOF\na\nb\nc\nEOF",
3893 "a\nexec ok\nb\nexec ok\nc\nexec ok\n",
3894 },
3895 {
3896 "echo file1 >f; echo file2 >>f; while read a; do echo $a; done <f",
3897 "file1\nfile2\n",
3898 },
3899 // TODO: our final exit status here isn't right.
3900 // {
3901 // "while read a; do echo $a; GOSH_CMD=print_fail $GOSH_PROG; done <<< 'a\nb\nc'",
3902 // "a\nexec fail\nb\nexec fail\nc\nexec fail\nexit status 1",
3903 // },
3904 {
3905 `read -r a <<< '\\'; echo "$a"`,
3906 "\\\\\n",
3907 },
3908 {
3909 "read -r a <<< '\\a\\b\\c'; echo $a",
3910 "\\a\\b\\c\n",
3911 },
3912 {
3913 "IFS=: read a b c <<< '1:2:3'; echo $a; echo $b; echo $c",
3914 "1\n2\n3\n",
3915 },
3916 {
3917 "IFS=: read a b c <<< '1\\:2:3'; echo \"$a\"; echo $b; echo $c",
3918 "1:2\n3\n\n",
3919 },
3920 {
3921 `read x <<< ' a b '; echo "[$x]"`,
3922 "[a b]\n",
3923 },
3924 {
3925 `IFS=' :' read x <<< ' :a b: '; echo "[$x]"`,
3926 "[:a b:]\n",
3927 },
3928 {
3929 `IFS=: read x <<< ':a:b:'; echo "[$x]"`,
3930 "[:a:b:]\n",
3931 },
3932 {
3933 `read <<< ' a \b '; echo "[$REPLY]"; read -r <<< ' a\b '; echo "[$REPLY]"`,
3934 "[ a b ]\n[ a\\b ]\n",
3935 },
3936 {
3937 "read -p",
3938 "read: -p: option requires an argument\nexit status 2 #JUSTERR",
3939 },
3940 {
3941 "read -X -p",
3942 "read: invalid option \"-X\"\nexit status 2 #JUSTERR",
3943 },
3944 {
3945 "read -p 'Display me as a prompt. Continue? (y/n) ' choice <<< 'y'; echo $choice",
3946 "Display me as a prompt. Continue? (y/n) y\n #IGNORE bash requires a terminal",
3947 },
3948 {
3949 "read -r -p 'Prompt and raw flag together: ' a <<< '\\a\\b\\c'; echo $a",
3950 "Prompt and raw flag together: \\a\\b\\c\n #IGNORE bash requires a terminal",
3951 },
3952
3953 // read -s
3954 {
3955 "read -r -s x <<< hi; echo \"[$x]\"",
3956 "[hi]\n",
3957 },
3958 {
3959 "printf 'a b\\n' | { read -s -r a b; echo \"[$a][$b]\"; }",
3960 "[a][b]\n",
3961 },
3962
3963 // read -a
3964 {
3965 `echo "1 2 3" | { read -a arr; echo "${arr[0]} ${arr[1]} ${arr[2]}"; }`,
3966 "1 2 3\n",
3967 },
3968 {
3969 `echo "a b c" | { read -a arr; echo "${#arr[@]}"; }`,
3970 "3\n",
3971 },
3972 {
3973 `echo "" | { read -a arr; echo "${#arr[@]}"; }`,
3974 "0\n",
3975 },
3976 {
3977 `echo 'a\tb' | { read -ra arr; echo "${#arr[@]} ${arr[0]}"; }`,
3978 "1 a\\tb\n",
3979 },
3980 {
3981 `a=a; echo | (read a; echo -n "$a")`,
3982 "",
3983 },
3984 {
3985 `a=b; read a < /dev/null; echo -n "$a"`,
3986 "",
3987 },
3988 {
3989 "a=c; echo x | (read a; echo -n $a)",
3990 "x",
3991 },
3992 {
3993 "a=d; echo -n y | (read a; echo -n $a)",
3994 "y",
3995 },
3996
3997 // getopts
3998 {
3999 "getopts",
4000 "getopts: usage: getopts optstring name [arg ...]\nexit status 2",
4001 },
4002 {
4003 "getopts a a:b",
4004 "getopts: invalid identifier: \"a:b\"\nexit status 2 #JUSTERR",
4005 },
4006 {
4007 "getopts abc opt -a; echo $opt; $optarg",
4008 "a\n",
4009 },
4010 {
4011 "getopts abc opt -z",
4012 "getopts: illegal option -- \"z\"\n #IGNORE",
4013 },
4014 {
4015 "getopts a: opt -a",
4016 "getopts: option requires an argument -- \"a\"\n #IGNORE",
4017 },
4018 {
4019 "getopts :abc opt -z; echo $opt; echo $OPTARG",
4020 "?\nz\n",
4021 },
4022 {
4023 "getopts :a: opt -a; echo $opt; echo $OPTARG",
4024 ":\na\n",
4025 },
4026 {
4027 "getopts abc opt foo -a; echo $opt; echo $OPTIND",
4028 "?\n1\n",
4029 },
4030 {
4031 "getopts abc opt -a foo; echo $opt; echo $OPTIND",
4032 "a\n2\n",
4033 },
4034 {
4035 "OPTIND=3; getopts abc opt -a -b -c; echo $opt;",
4036 "c\n",
4037 },
4038 {
4039 "OPTIND=100; getopts abc opt -a -b -c; echo $opt;",
4040 "?\n",
4041 },
4042 {
4043 "OPTIND=foo; getopts abc opt -a -b -c; echo $opt;",
4044 "a\n",
4045 },
4046 {
4047 "while getopts ab:c opt -c -b arg -a foo; do echo $opt $OPTARG $OPTIND; done",
4048 "c 2\nb arg 4\na 5\n",
4049 },
4050 {
4051 "while getopts abc opt -ba -c foo; do echo $opt $OPTARG $OPTIND; done",
4052 "b 1\na 2\nc 3\n",
4053 },
4054 {
4055 "while getopts ab: opt -a -bval -a; do echo $opt $OPTARG $OPTIND; done",
4056 "a 2\nb val 3\na 4\n",
4057 },
4058 {
4059 "while getopts b: opt -bval foo; do echo $opt $OPTARG $OPTIND; done",
4060 "b val 2\n",
4061 },
4062 {
4063 "while getopts ab: opt -ab val; do echo $opt $OPTARG $OPTIND; done",
4064 "a 1\nb val 3\n",
4065 },
4066 {
4067 "a() { while getopts abc: opt; do echo $opt $OPTARG; done }; a -a -b -c arg",
4068 "a\nb\nc arg\n",
4069 },
4070 // mapfile
4071 {
4072 "mapfile <<EOF\na\nb\nc\nEOF\n" + `for x in "${MAPFILE[@]}"; do echo "$x"; done`,
4073 "a\n\nb\n\nc\n\n",
4074 },
4075 {
4076 "mapfile -t <<EOF\na\nb\nc\nEOF\n" + `for x in "${MAPFILE[@]}"; do echo "$x"; done`,
4077 "a\nb\nc\n",
4078 },
4079 {
4080 "mapfile -t -d b <<EOF\nabc\nEOF\n" + `for x in "${MAPFILE[@]}"; do echo "$x"; done`,
4081 "a\nc\n\n",
4082 },
4083 {
4084 "mapfile -t butter <<EOF\na\nb\nc\nEOF\n" + `for x in "${butter[@]}"; do echo "$x"; done`,
4085 "a\nb\nc\n",
4086 },
4087 }
4088
4089 var runTestsUnix = []runTest{
4090 {"[[ -n $PPID && $PPID -ge 0 ]]", ""}, // can be 0 if running as the init process
4091 {
4092 // no root user on windows
4093 "[[ ~root == '~root' ]]",
4094 "exit status 1",
4095 },
4096
4097 // windows does not support paths with '*'
4098 {
4099 "mkdir -p '*/a.z' 'b/a.z'; cd '*'; set -- *.z; echo $#",
4100 "1\n",
4101 },
4102 {
4103 "mkdir -p 'a-*/d'; test -d $PWD/a-*/*",
4104 "",
4105 },
4106
4107 // windows does not reliably track last-access time, so -N is unix-only
4108 {
4109 ">a; cat a; sleep 0.01; echo 'Hello' >> a; test -N a && echo yes",
4110 "yes\n",
4111 },
4112 {
4113 "test -N nonexistent",
4114 "exit status 1",
4115 },
4116 {
4117 ">a; sleep 0.01; cat a; test -N a; echo $?",
4118 "1\n",
4119 },
4120
4121 // no fifos on windows
4122 {
4123 "[ -p a ] && echo x; mkfifo a; [ -p a ] && echo y",
4124 "y\n",
4125 },
4126 {
4127 "[[ -p a ]] && echo x; mkfifo a; [[ -p a ]] && echo y",
4128 "y\n",
4129 },
4130
4131 {"sh() { :; }; sh -c 'echo foo'", ""},
4132 {"sh() { :; }; command sh -c 'echo foo'", "foo\n"},
4133
4134 // files without a shebang line are run as shell scripts; see issue #1065
4135 {
4136 "echo 'echo foo' >a; chmod +x a; ./a",
4137 "foo\n",
4138 },
4139 {
4140 "echo 'echo $#: $1' >a; chmod +x a; ./a one two",
4141 "2: one\n",
4142 },
4143 {
4144 "echo 'echo \"[$foo][$bar]\"' >a; chmod +x a; foo=1; export bar=2; ./a",
4145 "[][2]\n",
4146 },
4147 {
4148 "echo 'exit 5' >a; chmod +x a; ./a",
4149 "exit status 5",
4150 },
4151 {
4152 "printf '\\0\\n' >a; chmod +x a; ./a",
4153 "./a: cannot execute binary file\nexit status 126 #JUSTERR",
4154 },
4155 {
4156 "echo 'if' >a; chmod +x a; ./a",
4157 "./a:1:1: `if` must be followed by a statement list\nexit status 2 #JUSTERR",
4158 },
4159
4160 // chmod is practically useless on Windows
4161 {
4162 "[ -x a ] && echo x; >a; chmod 0755 a; [ -x a ] && echo y",
4163 "y\n",
4164 },
4165 {
4166 "[[ -x a ]] && echo x; >a; chmod 0755 a; [[ -x a ]] && echo y",
4167 "y\n",
4168 },
4169 {
4170 ">a; [ -k a ] && echo x; chmod +t a; [ -k a ] && echo y",
4171 "y\n",
4172 },
4173 {
4174 ">a; [ -u a ] && echo x; chmod u+s a; [ -u a ] && echo y",
4175 "y\n",
4176 },
4177 {
4178 ">a; [ -g a ] && echo x; chmod g+s a; [ -g a ] && echo y",
4179 "y\n",
4180 },
4181 {
4182 ">a; [[ -k a ]] && echo x; chmod +t a; [[ -k a ]] && echo y",
4183 "y\n",
4184 },
4185 {
4186 ">a; [[ -u a ]] && echo x; chmod u+s a; [[ -u a ]] && echo y",
4187 "y\n",
4188 },
4189 {
4190 ">a; [[ -g a ]] && echo x; chmod g+s a; [[ -g a ]] && echo y",
4191 "y\n",
4192 },
4193 {
4194 `mkdir a; chmod 0100 a; cd a`,
4195 "",
4196 },
4197 // Note that these will succeed if we're root.
4198 {
4199 `mkdir a; chmod 0000 a; cd a`,
4200 "cd: permission denied: \"a\"\nexit status 1 #JUSTERR",
4201 },
4202 {
4203 `mkdir a; chmod 0222 a; cd a`,
4204 "cd: permission denied: \"a\"\nexit status 1 #JUSTERR",
4205 },
4206 {
4207 `mkdir a; chmod 0444 a; cd a`,
4208 "cd: permission denied: \"a\"\nexit status 1 #JUSTERR",
4209 },
4210 {
4211 `mkdir a; chmod 0010 a; cd a`,
4212 "cd: permission denied: \"a\"\nexit status 1 #JUSTERR",
4213 },
4214 {
4215 `mkdir a; chmod 0001 a; cd a`,
4216 "cd: permission denied: \"a\"\nexit status 1 #JUSTERR",
4217 },
4218 {
4219 `unset UID`,
4220 "UID: readonly variable\n #IGNORE",
4221 },
4222 {
4223 `test -n "$EUID" && echo OK`,
4224 "OK\n",
4225 },
4226 {
4227 `set EUID=newvalue; test EUID != newvalue && echo OK || echo EUID=$EUID`,
4228 "OK\n",
4229 },
4230 {
4231 `unset EUID`,
4232 "EUID: readonly variable\n #IGNORE",
4233 },
4234 // GID is not set in bash
4235 {
4236 `unset GID`,
4237 "GID: readonly variable\n #IGNORE",
4238 },
4239 {
4240 `[[ -z $GID ]] && echo "GID not set"`,
4241 "exit status 1 #JUSTERR #IGNORE",
4242 },
4243
4244 // Unix-y PATH
4245 {
4246 "PATH=; bash -c 'echo foo'",
4247 "\"bash\": executable file not found in $PATH\nexit status 127 #JUSTERR",
4248 },
4249 {
4250 "cd /; sure/is/missing",
4251 "stat /sure/is/missing: no such file or directory\nexit status 127 #JUSTERR",
4252 },
4253 {
4254 "echo '#!/bin/sh\necho b' >a; chmod 0755 a; PATH=; a",
4255 "b\n",
4256 },
4257 {
4258 "mkdir c; cd c; echo '#!/bin/sh\necho b' >a; chmod 0755 a; PATH=; a",
4259 "b\n",
4260 },
4261 {
4262 "mkdir c; echo '#!/bin/sh\necho b' >c/a; chmod 0755 c/a; c/a",
4263 "b\n",
4264 },
4265 {
4266 "GOSH_CMD=lookpath $GOSH_PROG",
4267 "sh found\n",
4268 },
4269
4270 // error strings which are too different on Windows
4271 {
4272 "echo foo >/shouldnotexist/file",
4273 "open /shouldnotexist/file: no such file or directory\nexit status 1 #JUSTERR",
4274 },
4275 {
4276 "set -e; echo foo >/shouldnotexist/file; echo foo",
4277 "open /shouldnotexist/file: no such file or directory\nexit status 1 #JUSTERR",
4278 },
4279
4280 // process substitution; named pipes (fifos) are a TODO for windows
4281 {
4282 "sed 's/o/e/g' <(echo foo bar)",
4283 "fee bar\n",
4284 },
4285 {
4286 "cat <(echo foo) <(echo bar) <(echo baz)",
4287 "foo\nbar\nbaz\n",
4288 },
4289 {
4290 "cat <(cat <(echo nested))",
4291 "nested\n",
4292 },
4293 {
4294 // The tests here use "wait" because otherwise the parent may finish before
4295 // the subprocess has had time to process the input and print the result.
4296 "echo foo bar > >(sed 's/o/e/g'); wait",
4297 "fee bar\n",
4298 },
4299 {
4300 "echo foo bar | tee >(sed 's/o/e/g') >/dev/null; wait",
4301 "fee bar\n",
4302 },
4303 {
4304 "echo nested > >(cat > >(cat); wait); wait",
4305 "nested\n",
4306 },
4307 {
4308 "cat <(exit 0); wait $!; echo $?",
4309 "0\n",
4310 },
4311 {
4312 "cat <(exit 5); wait $!; echo $?",
4313 "5\n",
4314 },
4315 {
4316 // The reader here does not consume the named pipe.
4317 "test -e <(echo foo)",
4318 "",
4319 },
4320 // echo trace
4321 {
4322 `set -x; animals=("dog", "cat", "otter"); echo "hello ${animals[*]}"`,
4323 `+ animals=("dog", "cat", "otter")
4324 + echo 'hello dog, cat, otter'
4325 hello dog, cat, otter
4326 `,
4327 },
4328 {
4329 `set -x; s="always print a decimal point for %e, %E, %f, %F, %g and %G; do not remove trailing zeros for %g and %G"; echo "$s"`,
4330 `+ s='always print a decimal point for %e, %E, %f, %F, %g and %G; do not remove trailing zeros for %g and %G'
4331 + echo 'always print a decimal point for %e, %E, %f, %F, %g and %G; do not remove trailing zeros for %g and %G'
4332 always print a decimal point for %e, %E, %f, %F, %g and %G; do not remove trailing zeros for %g and %G
4333 `,
4334 },
4335 {
4336 `set -x
4337 x=without; echo "$x"
4338 x="double quote"; echo "$x"
4339 x='single quote'; echo "$x"`,
4340 `+ x=without
4341 + echo without
4342 without
4343 + x='double quote'
4344 + echo 'double quote'
4345 double quote
4346 + x='single quote'
4347 + echo 'single quote'
4348 single quote
4349 `,
4350 },
4351 // for trace
4352 {
4353 `set -x
4354 exec >/dev/null
4355 echo "trace should go to stderr"`,
4356 `+ exec
4357 + echo 'trace should go to stderr'
4358 `,
4359 },
4360 {
4361 `set -x
4362 animals=(dog, cat, otter)
4363 for i in ${animals[@]}
4364 do
4365 echo "hello ${i}"
4366 done
4367 `,
4368 `+ animals=(dog, cat, otter)
4369 + for i in ${animals[@]}
4370 + echo 'hello dog,'
4371 hello dog,
4372 + for i in ${animals[@]}
4373 + echo 'hello cat,'
4374 hello cat,
4375 + for i in ${animals[@]}
4376 + echo 'hello otter'
4377 hello otter
4378 `,
4379 },
4380 {
4381 `set -x
4382 loop() {
4383 for i do
4384 echo "something with $i"
4385 done
4386 }
4387 loop 1 2 3`,
4388 `+ loop 1 2 3
4389 + for i in "$@"
4390 + echo 'something with 1'
4391 something with 1
4392 + for i in "$@"
4393 + echo 'something with 2'
4394 something with 2
4395 + for i in "$@"
4396 + echo 'something with 3'
4397 something with 3
4398 `,
4399 },
4400 {
4401 `set -x; animals=(dog, cat, otter); for i in ${animals[@]}; do echo "hello ${i}"; done`,
4402 `+ animals=(dog, cat, otter)
4403 + for i in ${animals[@]}
4404 + echo 'hello dog,'
4405 hello dog,
4406 + for i in ${animals[@]}
4407 + echo 'hello cat,'
4408 hello cat,
4409 + for i in ${animals[@]}
4410 + echo 'hello otter'
4411 hello otter
4412 `,
4413 },
4414 {
4415 "set -x; set -e; echo hi",
4416 "+ set -e\n+ echo hi\nhi\n",
4417 },
4418 {
4419 "set -x; set +x; echo hi",
4420 "+ set +x\nhi\n",
4421 },
4422 {
4423 // TODO: bash prints `a[1]=z`, including the subscript.
4424 `set -x; a=(x y); a[1]=z`,
4425 "+ a=(x y)\n+ a=z\n #IGNORE",
4426 },
4427 {
4428 // TODO: bash prints `a+=bar`, that is, the value being appended
4429 // rather than the resulting value.
4430 `set -x; a=foo; a+=bar`,
4431 "+ a=foo\n+ a=foobar\n #IGNORE",
4432 },
4433 {
4434 `set -x; a=(x); a+=(y)`,
4435 "+ a=(x)\n+ a+=(y)\n",
4436 },
4437 {
4438 `set -x; a=x"y"$z b=(foo bar $none '')`,
4439 "+ a=xy\n+ b=(foo bar $none '')\n",
4440 },
4441 {
4442 `set -x; for i in a b; do echo $i; done`,
4443 `+ for i in a b
4444 + echo a
4445 a
4446 + for i in a b
4447 + echo b
4448 b
4449 `,
4450 },
4451 {
4452 `set -x; for i in $none_a $none_b; do echo $i; done`,
4453 ``,
4454 },
4455 // case trace
4456 {
4457 `set -x; pet=dog; case $pet in 'dog') echo "barks";; *) echo "unknown";; esac`,
4458 `+ pet=dog
4459 + case $pet in
4460 + echo barks
4461 barks
4462 `,
4463 },
4464 {
4465 `set -x
4466 pet="dog"
4467 case $pet in
4468 dog)
4469 echo "barks"
4470 ;;
4471 *)
4472 echo "unknown"
4473 ;;
4474 esac`,
4475 `+ pet=dog
4476 + case $pet in
4477 + echo barks
4478 barks
4479 `,
4480 },
4481 // arithmetic
4482 {
4483 `set -x
4484 a=$(( 4 + 5 )); echo $a
4485 a=$((3+5)); echo $a`,
4486 `+ a=9
4487 + echo 9
4488 9
4489 + a=8
4490 + echo 8
4491 8
4492 `,
4493 },
4494 {
4495 `set -x;
4496 let a=5+4; echo $a
4497 let "a = 5 + 4"; echo $a
4498 let a++; echo $a`,
4499 `+ let a=5+4
4500 + echo 9
4501 9
4502 + let 'a = 5 + 4'
4503 + echo 9
4504 9
4505 + let a++
4506 + echo 10
4507 10
4508 `,
4509 },
4510 {
4511 `set -x; let a=1 b=2`,
4512 "+ let a=1 b=2\n",
4513 },
4514 {
4515 // Note that bash cannot parse `let (a=3)` at all.
4516 `set -x; let (a=3)`,
4517 "+ let (a = 3)\n #IGNORE",
4518 },
4519 // functions
4520 {
4521 `set -x; function with_function () { echo 'hello, world'; }; with_function`,
4522 `+ with_function
4523 + echo 'hello, world'
4524 hello, world
4525 `,
4526 },
4527 {
4528 `set -x; without_function () { echo 'hello, world'; }; without_function`,
4529 `+ without_function
4530 + echo 'hello, world'
4531 hello, world
4532 `,
4533 },
4534 {
4535 // globbing wildcard as function name
4536 `@() { echo "$@"; }; @ lala; function +() { echo "$@"; }; + foo`,
4537 "lala\nfoo\n",
4538 },
4539 {
4540 ` @() { echo "$@"; }; @ lala;`,
4541 "lala\n",
4542 },
4543 {
4544 // globbing wildcard as function name but with space after the name
4545 `+ () { echo "$@"; }; + foo; @ () { echo "$@"; }; @ lala; ? () { echo "$@"; }; ? bar`,
4546 "foo\nlala\nbar\n",
4547 },
4548 // mapfile, no process substitution yet on Windows
4549 {
4550 `mapfile -t -d "" < <(printf "a\0b\n"); for x in "${MAPFILE[@]}"; do echo "$x"; done`,
4551 "a\nb\n\n",
4552 },
4553 // Windows does not support having a `\n` in a filename
4554 {
4555 `> $'bar\nbaz'; echo bar*baz`,
4556 "bar\nbaz\n",
4557 },
4558 }
4559
4560 var runTestsWindows = []runTest{
4561 {"[[ -n $PPID || $PPID -gt 0 ]]", ""}, // os.Getppid can be 0 on windows
4562 {"cmd() { :; }; cmd /c 'echo foo'", ""},
4563 {"cmd() { :; }; command cmd /c 'echo foo'", "foo\r\n"},
4564 {
4565 "GOSH_CMD=lookpath $GOSH_PROG",
4566 "cmd found\n",
4567 },
4568 {
4569 "localCase=camel; LocalCase=pascal; echo $localcase",
4570 "pascal\n",
4571 },
4572 {
4573 // Matching the env var name set as a global
4574 // in a case sensitive way.
4575 "$ENV_PROG | grep -i '^mixedCase_interp'",
4576 "mixedCase_INTERP_GLOBAL=value\n",
4577 },
4578 {
4579 // Overwriting the env var set as a global
4580 // in a case insensitive way.
4581 "MIXEDCASE_interp_global=replaced; echo $MIXEDCASE_interp_GLOBAL",
4582 "replaced\n",
4583 },
4584 {
4585 "MIXEDCASE_interp_global=replaced; $ENV_PROG | grep -i '^mixedcase_interp'",
4586 "MIXEDCASE_interp_global=replaced\n",
4587 },
4588 }
4589
4590 // These tests are specific to 64-bit architectures, and that's fine. We don't
4591 // need to add explicit versions for 32-bit.
4592 var runTests64bit = []runTest{
4593 {"printf %i,%u -3 -3", "-3,18446744073709551613"},
4594 {"printf %o -3", "1777777777777777777775"},
4595 {"printf %x -3", "fffffffffffffffd"},
4596 }
4597
4598 func init() {
4599 switch {
4600 case runtime.GOOS == "windows":
4601 runTests = append(runTests, runTestsWindows...)
4602 case runtime.GOOS == "js":
4603 // Neither Unix-y nor Windows: js/wasm has no subprocesses,
4604 // and its file modes and syscall errors differ from Unix.
4605 default: // Unix-y
4606 runTests = append(runTests, runTestsUnix...)
4607 }
4608 if bits.UintSize == 64 {
4609 runTests = append(runTests, runTests64bit...)
4610 }
4611 }
4612
4613 // ln -s: wine doesn't implement symlinks; see https://bugs.winehq.org/show_bug.cgi?id=44948
4614 // process substitutions are not supported on Windows
4615 var skipOnWindows = regexp.MustCompile(`ln -s|<\(`)
4616
4617 // process substitutions seemflaky on mac; see https://github.com/mvdan/sh/issues/576
4618 var skipOnMac = regexp.MustCompile(`>\(|<\(`)
4619
4620 // canExec reports whether the platform can run external programs.
4621 // js/wasm has no subprocesses at all.
4622 const canExec = runtime.GOOS != "js"
4623
4624 // Without subprocesses we can't run the test binary as a helper program,
4625 // nor any external program, nor create the named pipes used by process
4626 // substitutions.
4627 var skipWithoutExec = regexp.MustCompile(`GOSH_PROG|ENV_PROG|PATH_PROG|>\(|<\(`)
4628
4629 func skipIfUnsupported(tb testing.TB, src string) {
4630 switch {
4631 case runtime.GOOS == "windows" && skipOnWindows.MatchString(src):
4632 tb.Skipf("skipping non-portable test on windows")
4633 case runtime.GOOS == "darwin" && skipOnMac.MatchString(src):
4634 tb.Skipf("skipping non-portable test on mac")
4635 case !canExec && skipWithoutExec.MatchString(src):
4636 tb.Skipf("skipping test needing subprocesses on %s", runtime.GOOS)
4637 }
4638 }
4639
4640 func TestRunnerRun(t *testing.T) {
4641 t.Parallel()
4642
4643 p := syntax.NewParser()
4644 for _, c := range runTests {
4645 t.Run("", func(t *testing.T) {
4646 skipIfUnsupported(t, c.in)
4647 t.Logf("input: %q", c.in)
4648
4649 // Parse first, as we reuse a single parser.
4650 file := parse(t, p, c.in)
4651
4652 t.Parallel()
4653
4654 tdir := t.TempDir()
4655 var cb concBuffer
4656 r, err := interp.New(interp.Dir(tdir), interp.StdIO(nil, &cb, &cb),
4657 // TODO: why does this make some tests hang?
4658 // interp.Env(expand.ListEnviron(append(os.Environ(),
4659 // "foo_NULL_BAR=foo\x00bar")...)),
4660 interp.ExecHandlers(testExecHandler),
4661 )
4662 if err != nil {
4663 t.Fatal(err)
4664 }
4665 ctx, cancel := context.WithTimeout(t.Context(), runnerRunTimeout)
4666 defer cancel()
4667 if err := r.Run(ctx, file); err != nil {
4668 cb.WriteString(err.Error())
4669 }
4670
4671 // Some builtins like "pushd" can show absolute paths as part of error messages.
4672 // Allow a very simple search-and-replace for the equivalent to "$PWD/a".
4673 want := strings.ReplaceAll(c.want, "ABS_PATH_A", fmt.Sprintf("%q", filepath.Join(tdir, "a")))
4674
4675 if i := strings.Index(want, " #"); i >= 0 {
4676 want = want[:i]
4677 }
4678 if got := cb.String(); got != want {
4679 if len(got) > 200 {
4680 got = "…" + got[len(got)-200:]
4681 }
4682 t.Fatalf("wrong output in %q:\nwant: %q\ngot: %q",
4683 c.in, want, got)
4684 }
4685 })
4686 }
4687 }
4688
4689 func TestRunnerUnsupported(t *testing.T) {
4690 t.Parallel()
4691
4692 // Features from language variants that the interpreter does not
4693 // support, such as zsh, should error rather than panic.
4694 tests := []struct {
4695 lang syntax.LangVariant
4696 in string
4697 want string
4698 }{
4699 {syntax.LangZsh, "echo x${}y", "unsupported\n"},
4700 {syntax.LangZsh, `echo "${}"`, "unsupported\n"},
4701 {syntax.LangZsh, "echo ${:-foo}", "unsupported\n"},
4702 {syntax.LangZsh, "echo ${+a}", "unsupported\n"},
4703 {syntax.LangZsh, "a=abc; echo ${a[(r)b]}", "unsupported\n"},
4704 {syntax.LangZsh, "() { echo anon; }", "unsupported\nexit status 1"},
4705 {syntax.LangZsh, "function { echo anon; }", "unsupported\nexit status 1"},
4706 {syntax.LangZsh, "function f g { echo multi; }", "unsupported\nexit status 1"},
4707 {syntax.LangZsh, "cat =(echo hi)", "unsupported\n"},
4708 {syntax.LangMirBSDKorn, "echo ${%a}", "unsupported\n"},
4709 }
4710 for _, tc := range tests {
4711 t.Run("", func(t *testing.T) {
4712 t.Parallel()
4713 t.Logf("input: %q", tc.in)
4714 p := syntax.NewParser(syntax.Variant(tc.lang))
4715 file := parse(t, p, tc.in)
4716 var cb concBuffer
4717 r, err := interp.New(interp.StdIO(nil, &cb, &cb))
4718 if err != nil {
4719 t.Fatal(err)
4720 }
4721 ctx, cancel := context.WithTimeout(t.Context(), runnerRunTimeout)
4722 defer cancel()
4723 if err := r.Run(ctx, file); err != nil {
4724 cb.WriteString(err.Error())
4725 }
4726 if got := cb.String(); got != tc.want {
4727 t.Fatalf("wrong output in %q:\nwant: %q\ngot: %q",
4728 tc.in, tc.want, got)
4729 }
4730 })
4731 }
4732 }
4733
4734 func readLines(hc interp.HandlerContext) ([][]byte, error) {
4735 bs, err := io.ReadAll(hc.Stdin)
4736 if err != nil {
4737 return nil, err
4738 }
4739 if runtime.GOOS == "windows" {
4740 bs = bytes.ReplaceAll(bs, []byte("\r\n"), []byte("\n"))
4741 }
4742 bs = bytes.TrimSuffix(bs, []byte("\n"))
4743 return bytes.Split(bs, []byte("\n")), nil
4744 }
4745
4746 func absPath(dir, path string) string {
4747 if path == "" {
4748 return ""
4749 }
4750 if !filepath.IsAbs(path) {
4751 path = filepath.Join(dir, path)
4752 }
4753 // Keep in sync with interp's own absPath, which explains the cleaning.
4754 return filepath.Clean(path)
4755 }
4756
4757 var testBuiltinsMap = map[string]func(interp.HandlerContext, []string) error{
4758 "cat": func(hc interp.HandlerContext, args []string) error {
4759 if len(args) == 0 {
4760 if hc.Stdin == nil || hc.Stdout == nil {
4761 return nil
4762 }
4763 _, err := io.Copy(hc.Stdout, hc.Stdin)
4764 return err
4765 }
4766 for _, arg := range args {
4767 path := absPath(hc.Dir, arg)
4768 f, err := os.Open(path)
4769 if err != nil {
4770 return err
4771 }
4772 _, err = io.Copy(hc.Stdout, f)
4773 f.Close()
4774 if err != nil {
4775 return err
4776 }
4777 }
4778 return nil
4779 },
4780 "wc": func(hc interp.HandlerContext, args []string) error {
4781 bs, err := io.ReadAll(hc.Stdin)
4782 if err != nil {
4783 return err
4784 }
4785 if len(args) == 0 {
4786 fmt.Fprintf(hc.Stdout, "%7d", bytes.Count(bs, []byte("\n")))
4787 fmt.Fprintf(hc.Stdout, "%8d", len(bytes.Fields(bs)))
4788 fmt.Fprintf(hc.Stdout, "%8d\n", len(bs))
4789 } else if args[0] == "-c" {
4790 fmt.Fprintln(hc.Stdout, len(bs))
4791 } else if args[0] == "-l" {
4792 fmt.Fprintln(hc.Stdout, bytes.Count(bs, []byte("\n")))
4793 }
4794 return nil
4795 },
4796 "tr": func(hc interp.HandlerContext, args []string) error {
4797 if len(args) != 2 || len(args[1]) != 1 {
4798 return fmt.Errorf("usage: tr [-s -d] [character]")
4799 }
4800 squeeze := args[0] == "-s"
4801 char := args[1][0]
4802 bs, err := io.ReadAll(hc.Stdin)
4803 if err != nil {
4804 return err
4805 }
4806 for {
4807 i := bytes.IndexByte(bs, char)
4808 if i < 0 {
4809 hc.Stdout.Write(bs) // remaining
4810 break
4811 }
4812 hc.Stdout.Write(bs[:i]) // up to char
4813 bs = bs[i+1:]
4814
4815 bs = bytes.TrimLeft(bs, string(char)) // remove repeats
4816 if squeeze {
4817 hc.Stdout.Write([]byte{char})
4818 }
4819 }
4820 return nil
4821 },
4822 "sort": func(hc interp.HandlerContext, args []string) error {
4823 lines, err := readLines(hc)
4824 if err != nil {
4825 return err
4826 }
4827 slices.SortFunc(lines, bytes.Compare)
4828 for _, line := range lines {
4829 fmt.Fprintf(hc.Stdout, "%s\n", line)
4830 }
4831 return nil
4832 },
4833 "grep": func(hc interp.HandlerContext, args []string) error {
4834 var rx *regexp.Regexp
4835 quiet := false
4836 caseInsensitive := false
4837 for _, arg := range args {
4838 if arg == "-q" {
4839 quiet = true
4840 } else if arg == "-i" {
4841 caseInsensitive = true
4842 } else if arg == "-E" {
4843 } else if rx == nil {
4844 if caseInsensitive {
4845 arg = "(?i)" + arg
4846 }
4847 rx = regexp.MustCompile(arg)
4848 } else {
4849 return fmt.Errorf("unexpected arg: %q", arg)
4850 }
4851 }
4852 lines, err := readLines(hc)
4853 if err != nil {
4854 return err
4855 }
4856 anyMatch := false
4857 for _, line := range lines {
4858 if rx.Match(line) {
4859 if quiet {
4860 return nil
4861 }
4862 anyMatch = true
4863 fmt.Fprintf(hc.Stdout, "%s\n", line)
4864 }
4865 }
4866 if !anyMatch {
4867 return interp.ExitStatus(1)
4868 }
4869 return nil
4870 },
4871 "sed": func(hc interp.HandlerContext, args []string) error {
4872 f := hc.Stdin
4873 switch len(args) {
4874 case 1:
4875 case 2:
4876 var err error
4877 f, err = os.Open(absPath(hc.Dir, args[1]))
4878 if err != nil {
4879 return err
4880 }
4881 default:
4882 return fmt.Errorf("usage: sed pattern [file]")
4883 }
4884 expr := args[0]
4885 if expr == "" || expr[0] != 's' {
4886 return fmt.Errorf("unimplemented")
4887 }
4888 sep := expr[1]
4889 expr = expr[2:]
4890 from := expr[:strings.IndexByte(expr, sep)]
4891 expr = expr[len(from)+1:]
4892 to := expr[:strings.IndexByte(expr, sep)]
4893 bs, err := io.ReadAll(f)
4894 if err != nil {
4895 return err
4896 }
4897 rx := regexp.MustCompile(from)
4898 bs = rx.ReplaceAllLiteral(bs, []byte(to))
4899 _, err = hc.Stdout.Write(bs)
4900 return err
4901 },
4902 "mkdir": func(hc interp.HandlerContext, args []string) error {
4903 for _, arg := range args {
4904 if arg == "-p" {
4905 continue
4906 }
4907 path := absPath(hc.Dir, arg)
4908 if err := os.MkdirAll(path, 0o777); err != nil {
4909 return err
4910 }
4911 }
4912 return nil
4913 },
4914 "rm": func(hc interp.HandlerContext, args []string) error {
4915 for _, arg := range args {
4916 if arg == "-r" {
4917 continue
4918 }
4919 path := absPath(hc.Dir, arg)
4920 if err := os.RemoveAll(path); err != nil {
4921 return err
4922 }
4923 }
4924 return nil
4925 },
4926 "ln": func(hc interp.HandlerContext, args []string) error {
4927 symbolic := args[0] == "-s"
4928 if symbolic {
4929 args = args[1:]
4930 }
4931 oldname := absPath(hc.Dir, args[0])
4932 newname := absPath(hc.Dir, args[1])
4933 if symbolic {
4934 return os.Symlink(oldname, newname)
4935 }
4936 return os.Link(oldname, newname)
4937 },
4938 "touch": func(hc interp.HandlerContext, args []string) error {
4939 filenames := args // create all arguments as filenames
4940
4941 newTime := time.Now()
4942 if args[0] == "-t" {
4943 if len(args) < 3 {
4944 return fmt.Errorf("usage: touch [-t [[CC]YY]MMDDhhmm[.SS]] file")
4945 }
4946 filenames = args[2:] // treat the rest of the args as filenames
4947
4948 arg := args[1]
4949 if len(arg) > 15 {
4950 return fmt.Errorf("usage: touch [-t [[CC]YY]MMDDhhmm[.SS]] file")
4951 }
4952 s, err := time.Parse("200601021504.05", arg)
4953 if err != nil {
4954 return err
4955 }
4956 newTime = s
4957 }
4958
4959 for _, arg := range filenames {
4960 if strings.HasPrefix(arg, "-") {
4961 return fmt.Errorf("usage: touch [-t [[CC]YY]MMDDhhmm[.SS]] file")
4962 }
4963 path := absPath(hc.Dir, arg)
4964 // create the file if it does not exist
4965 f, err := os.OpenFile(path, os.O_CREATE, 0o666)
4966 if err != nil {
4967 return err
4968 }
4969 f.Close()
4970 // change the modification and access time
4971 if err := os.Chtimes(path, newTime, newTime); err != nil {
4972 return err
4973 }
4974 }
4975 return nil
4976 },
4977 "sleep": func(hc interp.HandlerContext, args []string) error {
4978 for _, arg := range args {
4979 // assume and default unit to be in seconds
4980 d, err := time.ParseDuration(fmt.Sprintf("%ss", arg))
4981 if err != nil {
4982 return err
4983 }
4984 time.Sleep(d)
4985 }
4986 return nil
4987 },
4988 }
4989
4990 func testExecHandler(next interp.ExecHandlerFunc) interp.ExecHandlerFunc {
4991 return func(ctx context.Context, args []string) error {
4992 if fn := testBuiltinsMap[args[0]]; fn != nil {
4993 return fn(interp.HandlerCtx(ctx), args[1:])
4994 }
4995 return next(ctx, args)
4996 }
4997 }
4998
4999 // Same as the syntax package.
5000 var requireShells = os.Getenv("REQUIRE_SHELLS") == "1"
5001
5002 func TestRunnerRunConfirm(t *testing.T) {
5003 if testing.Short() {
5004 t.Skip("calling bash is slow")
5005 }
5006 if !hasBash53 {
5007 if requireShells {
5008 t.Fatal("bash 5.3 required to run")
5009 } else {
5010 t.Skip("bash 5.3 required to run")
5011 }
5012 }
5013 t.Parallel()
5014
5015 if runtime.GOOS == "windows" {
5016 // For example, it seems to treat environment variables as
5017 // case-sensitive, which isn't how Windows works.
5018 t.Skip("bash on Windows emulates Unix-y behavior")
5019 }
5020 for _, c := range runTests {
5021 t.Run("", func(t *testing.T) {
5022 if strings.Contains(c.want, " #IGNORE") {
5023 return
5024 }
5025 skipIfUnsupported(t, c.in)
5026 t.Parallel()
5027 tdir := t.TempDir()
5028 ctx, cancel := context.WithTimeout(t.Context(), runnerRunTimeout)
5029 defer cancel()
5030 cmd := exec.CommandContext(ctx, "bash")
5031 cmd.Dir = tdir
5032 cmd.Stdin = strings.NewReader(c.in)
5033 out, err := cmd.CombinedOutput()
5034 if strings.Contains(c.want, " #JUSTERR") {
5035 // bash sometimes exits with status code 0 and
5036 // stderr "bash: ..." for an error
5037 fauxErr := bytes.HasPrefix(out, []byte("bash:"))
5038 if err == nil && !fauxErr {
5039 t.Fatalf("wanted bash to error in %q", c.in)
5040 }
5041 return
5042 }
5043 got := string(out)
5044 if err != nil {
5045 got += err.Error()
5046 }
5047 if got != c.want {
5048 t.Fatalf("wrong bash output in %q:\nwant: %q\ngot: %q",
5049 c.in, c.want, got)
5050 }
5051 })
5052 }
5053 }
5054
5055 func TestRunnerOpts(t *testing.T) {
5056 t.Parallel()
5057
5058 withPath := func(strs ...string) func(*interp.Runner) error {
5059 prefix := []string{
5060 "PATH=" + os.Getenv("PATH"),
5061 "ENV_PROG=" + os.Getenv("ENV_PROG"),
5062 }
5063 return interp.Env(expand.ListEnviron(append(prefix, strs...)...))
5064 }
5065 opts := func(list ...interp.RunnerOption) []interp.RunnerOption {
5066 return list
5067 }
5068 cases := []struct {
5069 opts []interp.RunnerOption
5070 in, want string
5071 }{
5072 {
5073 nil,
5074 "$ENV_PROG | grep -i '^interp_global='",
5075 "INTERP_GLOBAL=value\n",
5076 },
5077 {
5078 opts(withPath()),
5079 "$ENV_PROG | grep -i '^interp_global='",
5080 "exit status 1",
5081 },
5082 {
5083 opts(withPath("INTERP_GLOBAL=bar")),
5084 "$ENV_PROG | grep -i '^interp_global='",
5085 "INTERP_GLOBAL=bar\n",
5086 },
5087 {
5088 opts(withPath("a=b")),
5089 "echo $a",
5090 "b\n",
5091 },
5092 {
5093 opts(withPath("A=b")),
5094 "$ENV_PROG | grep '^A='; echo $A",
5095 "A=b\nb\n",
5096 },
5097 {
5098 opts(withPath("A=b", "A=c")),
5099 "$ENV_PROG | grep '^A='; echo $A",
5100 "A=c\nc\n",
5101 },
5102 {
5103 opts(withPath("HOME=")),
5104 "echo $HOME",
5105 "\n",
5106 },
5107 {
5108 opts(withPath("PWD=foo")),
5109 "[[ $PWD == foo ]]",
5110 "exit status 1",
5111 },
5112 {
5113 opts(interp.Params("foo")),
5114 "echo $@",
5115 "foo\n",
5116 },
5117 {
5118 opts(interp.Params("-u", "--", "foo")),
5119 "echo $@; echo $unset",
5120 "foo\nunset: unbound variable\nexit status 1",
5121 },
5122 {
5123 opts(interp.Params("-u", "--", "foo")),
5124 "echo $@; echo ${unset:-default}",
5125 "foo\ndefault\n",
5126 },
5127 {
5128 opts(interp.Params("foo")),
5129 "set >/dev/null; echo $@",
5130 "foo\n",
5131 },
5132 {
5133 opts(interp.Params("foo")),
5134 "set -e; echo $@",
5135 "foo\n",
5136 },
5137 {
5138 opts(interp.Params("foo")),
5139 "set --; echo $@",
5140 "\n",
5141 },
5142 {
5143 opts(interp.Params("foo")),
5144 "set bar; echo $@",
5145 "bar\n",
5146 },
5147 {
5148 opts(interp.BashOpts()),
5149 "echo foo",
5150 "foo\n",
5151 },
5152 {
5153 opts(interp.BashOpts("-s", "expand_aliases")),
5154 "alias f='echo x'\nf",
5155 "x\n",
5156 },
5157 {
5158 opts(interp.BashOpts("-s", "extglob", "nullglob")),
5159 "[[ abc == @(abc|def) ]] && echo yes\necho no-match-*",
5160 "yes\n\n",
5161 },
5162 {
5163 opts(interp.BashOpts("-s", "globstar"), interp.BashOpts("-u", "globstar")),
5164 "shopt globstar | grep -q 'off$'",
5165 "",
5166 },
5167 {
5168 opts(interp.BashOpts("-o", "-s", "pipefail")),
5169 "false | true; echo $?",
5170 "1\n",
5171 },
5172 {
5173 opts(interp.BashOpts("-o", "-s", "noglob")),
5174 "echo *",
5175 "*\n",
5176 },
5177 {
5178 opts(interp.Env(expand.FuncEnviron(func(name string) string {
5179 if name == "foo" {
5180 return "bar"
5181 }
5182 return ""
5183 }))),
5184 "(echo $foo); echo x | echo $foo",
5185 "bar\nbar\n",
5186 },
5187 }
5188 p := syntax.NewParser()
5189 for _, c := range cases {
5190 t.Run("", func(t *testing.T) {
5191 skipIfUnsupported(t, c.in)
5192 file := parse(t, p, c.in)
5193 var cb concBuffer
5194 r, err := interp.New(append(c.opts,
5195 interp.StdIO(nil, &cb, &cb),
5196 interp.ExecHandlers(testExecHandler),
5197 )...)
5198 if err != nil {
5199 t.Fatal(err)
5200 }
5201 ctx, cancel := context.WithTimeout(t.Context(), runnerRunTimeout)
5202 defer cancel()
5203 if err := r.Run(ctx, file); err != nil {
5204 cb.WriteString(err.Error())
5205 }
5206 if got := cb.String(); got != c.want {
5207 t.Fatalf("wrong output in %q:\nwant: %q\ngot: %q",
5208 c.in, c.want, got)
5209 }
5210 })
5211 }
5212 }
5213
5214 func TestRunnerBashOpts(t *testing.T) {
5215 t.Parallel()
5216
5217 // Applying the option to an existing runner takes effect right away,
5218 // including for the options which affect expansion.
5219 file := parse(t, nil, "echo no-match-*")
5220 var b bytes.Buffer
5221 r, err := interp.New(interp.StdIO(nil, &b, &b))
5222 if err != nil {
5223 t.Fatal(err)
5224 }
5225 ctx, cancel := context.WithTimeout(t.Context(), runnerRunTimeout)
5226 defer cancel()
5227 if err := r.Run(ctx, file); err != nil {
5228 t.Fatal(err)
5229 }
5230 if err := interp.BashOpts("-s", "nullglob")(r); err != nil {
5231 t.Fatal(err)
5232 }
5233 if err := r.Run(ctx, file); err != nil {
5234 t.Fatal(err)
5235 }
5236 want := "no-match-*\n\n"
5237 if got := b.String(); got != want {
5238 t.Fatalf("\nwant: %q\ngot: %q", want, got)
5239 }
5240 }
5241
5242 func TestRunnerBashOptsErr(t *testing.T) {
5243 t.Parallel()
5244
5245 tests := []struct {
5246 args []string
5247 want string
5248 }{
5249 {[]string{"-z"}, `invalid option: "-z"`},
5250 {[]string{"-p"}, `invalid option: "-p"`},
5251 {[]string{"-o", "-s", "extglob"}, `invalid option name: "extglob"`},
5252 {[]string{"-s", "pipefail"}, `invalid option name: "pipefail"`},
5253 {[]string{"extglob"}, "either -s or -u must be given to set or unset options"},
5254 {[]string{"-s", "nosuchname"}, `invalid option name: "nosuchname"`},
5255 {[]string{"-s", "login_shell"}, `unsupported option: "login_shell"`},
5256 }
5257 for _, test := range tests {
5258 t.Run("", func(t *testing.T) {
5259 _, err := interp.New(interp.BashOpts(test.args...))
5260 if err == nil {
5261 t.Fatalf("BashOpts(%q) did not error", test.args)
5262 }
5263 if got := err.Error(); got != test.want {
5264 t.Fatalf("BashOpts(%q):\nwant: %q\ngot: %q", test.args, test.want, got)
5265 }
5266 })
5267 }
5268 }
5269
5270 func TestRunnerContext(t *testing.T) {
5271 t.Parallel()
5272
5273 cases := []string{
5274 "",
5275 "while true; do true; done",
5276 "until false; do true; done",
5277 "sleep 1000",
5278 "while true; do true; done & wait",
5279 "sleep 1000 & wait",
5280 "(while true; do true; done)",
5281 "$(while true; do true; done)",
5282 "while true; do true; done | while true; do true; done",
5283 }
5284 p := syntax.NewParser()
5285 for _, in := range cases {
5286 t.Run("", func(t *testing.T) {
5287 file := parse(t, p, in)
5288 ctx, cancel := context.WithCancel(t.Context())
5289 cancel()
5290 r, _ := interp.New()
5291 errChan := make(chan error)
5292 go func() {
5293 errChan <- r.Run(ctx, file)
5294 }()
5295
5296 timeout := 500 * time.Millisecond
5297 select {
5298 case err := <-errChan:
5299 if err != nil && err != ctx.Err() {
5300 t.Fatal("Runner did not use ctx.Err()")
5301 }
5302 case <-time.After(timeout):
5303 t.Fatalf("program was not killed in %s", timeout)
5304 }
5305 })
5306 }
5307 }
5308
5309 func TestCancelBlockedStdinRead(t *testing.T) {
5310 // "read -s" reads without echoing, which must still be cancellable.
5311 for _, in := range []string{"read x", "read -s x"} {
5312 t.Run("", func(t *testing.T) { testCancelBlockedStdinRead(t, in) })
5313 }
5314 }
5315
5316 func testCancelBlockedStdinRead(t *testing.T, in string) {
5317 if runtime.GOOS == "windows" {
5318 // TODO: Why is this? The [os.File.SetReadDeadline] docs seem to imply that it should work
5319 // across all major platforms, and the file polling implementation seems to be
5320 // for all posix platforms including Windows.
5321 // Our previous logic and tests with muesli/cancelreader did not test an os.Pipe
5322 // on Windows either, so skipping here is not any worse.
5323 t.Skip("os.Pipe on windows appears to not support cancellable reads")
5324 }
5325 if runtime.GOOS == "js" {
5326 t.Skip("js/wasm has no os.Pipe, and its reads can't be cancelled")
5327 }
5328 t.Parallel()
5329
5330 p := syntax.NewParser()
5331 file := parse(t, p, in)
5332 ctx, cancel := context.WithTimeout(t.Context(), 100*time.Millisecond)
5333 // Make the linter happy, even though we deliberately wait for the timeout.
5334 defer cancel()
5335
5336 stdinRead, stdinWrite, err := os.Pipe()
5337 if err != nil {
5338 t.Fatalf("Error calling os.Pipe: %v", err)
5339 }
5340 defer func() {
5341 stdinWrite.Close()
5342 stdinRead.Close()
5343 }()
5344 r, _ := interp.New(interp.StdIO(stdinRead, nil, nil))
5345 now := time.Now()
5346 errChan := make(chan error)
5347 go func() {
5348 errChan <- r.Run(ctx, file)
5349 }()
5350
5351 timeout := 500 * time.Millisecond
5352 select {
5353 case err := <-errChan:
5354 if err == nil || err.Error() != "exit status 1" || ctx.Err() != context.DeadlineExceeded {
5355 t.Fatalf("'read x' did not timeout correctly; err: %v, ctx.Err(): %v; dur: %v",
5356 err, ctx.Err(), time.Since(now))
5357 }
5358 case <-time.After(timeout):
5359 t.Fatalf("program was not killed in %s", timeout)
5360 }
5361 }
5362
5363 func TestRunnerAltNodes(t *testing.T) {
5364 t.Parallel()
5365
5366 in := "echo foo"
5367 file := parse(t, nil, in)
5368 want := "foo\n"
5369 nodes := []syntax.Node{
5370 file,
5371 file.Stmts[0],
5372 file.Stmts[0].Cmd,
5373 }
5374 for _, node := range nodes {
5375 var cb concBuffer
5376 r, _ := interp.New(interp.StdIO(nil, &cb, &cb))
5377 ctx, cancel := context.WithTimeout(t.Context(), runnerRunTimeout)
5378 defer cancel()
5379 if err := r.Run(ctx, node); err != nil {
5380 cb.WriteString(err.Error())
5381 }
5382 if got := cb.String(); got != want {
5383 t.Fatalf("wrong output in %q:\nwant: %q\ngot: %q",
5384 in, want, got)
5385 }
5386 }
5387 }
5388
5389 func TestRunnerDir(t *testing.T) {
5390 t.Parallel()
5391
5392 wd, err := os.Getwd()
5393 if err != nil {
5394 t.Fatal(err)
5395 }
5396 t.Run("Missing", func(t *testing.T) {
5397 _, err := interp.New(interp.Dir("missing"))
5398 if err == nil {
5399 t.Fatal("expected New to error when Dir is missing")
5400 }
5401 })
5402 t.Run("NotDir", func(t *testing.T) {
5403 _, err := interp.New(interp.Dir("interp_test.go"))
5404 if err == nil {
5405 t.Fatal("expected New to error when Dir is not a dir")
5406 }
5407 })
5408 t.Run("NotDirAbs", func(t *testing.T) {
5409 _, err := interp.New(interp.Dir(filepath.Join(wd, "interp_test.go")))
5410 if err == nil {
5411 t.Fatal("expected New to error when Dir is not a dir")
5412 }
5413 })
5414 t.Run("Relative", func(t *testing.T) {
5415 // On Windows, it's impossible to make a relative path from one
5416 // drive to another. Use the parent directory, as that's for
5417 // sure in the same drive as the current directory.
5418 rel := ".." + string(filepath.Separator)
5419 r, err := interp.New(interp.Dir(rel))
5420 if err != nil {
5421 t.Fatal(err)
5422 }
5423 if !filepath.IsAbs(r.Dir) {
5424 t.Errorf("Runner.Dir is not absolute")
5425 }
5426 })
5427 // Ensure that we treat symlinks and short paths properly, especially
5428 // with Dir and globbing.
5429 t.Run("SymlinkOrShortPath", func(t *testing.T) {
5430 tdir := t.TempDir()
5431
5432 realDir := filepath.Join(tdir, "real-long-dir-name")
5433 realFile := filepath.Join(realDir, "realfile")
5434
5435 if err := os.Mkdir(realDir, 0o777); err != nil {
5436 t.Fatal(err)
5437 }
5438 if err := os.WriteFile(realFile, []byte(""), 0o666); err != nil {
5439 t.Fatal(err)
5440 }
5441
5442 var altDir string
5443 if runtime.GOOS == "windows" {
5444 short, err := shortPathName(realDir)
5445 if err != nil {
5446 t.Fatal(err)
5447 }
5448 altDir = short
5449 // We replace tdir later, and it might have been shortened.
5450 tdir = filepath.Dir(altDir)
5451 } else {
5452 altDir = filepath.Join(tdir, "symlink")
5453 if err := os.Symlink(realDir, altDir); err != nil {
5454 t.Fatal(err)
5455 }
5456 }
5457
5458 var b bytes.Buffer
5459 r, err := interp.New(interp.Dir(altDir), interp.StdIO(nil, &b, &b))
5460 if err != nil {
5461 t.Fatal(err)
5462 }
5463 file := parse(t, nil, "echo $PWD $PWD/*")
5464 ctx, cancel := context.WithTimeout(t.Context(), runnerRunTimeout)
5465 defer cancel()
5466 if err := r.Run(ctx, file); err != nil {
5467 t.Fatal(err)
5468 }
5469 got := b.String()
5470 got = strings.ReplaceAll(got, tdir, "")
5471 got = strings.TrimSpace(got)
5472 want := `/symlink /symlink/realfile`
5473 if runtime.GOOS == "windows" {
5474 want = `\\REAL.{4} \\REAL.{4}\\realfile`
5475 }
5476 if !regexp.MustCompile(want).MatchString(got) {
5477 t.Fatalf("\nwant regexp: %q\ngot: %q", want, got)
5478 }
5479 })
5480 }
5481
5482 func TestRunnerIncremental(t *testing.T) {
5483 t.Parallel()
5484
5485 file := parse(t, nil, "echo foo; false; echo bar; exit 0; echo baz")
5486 want := "foo\nbar\n"
5487 var b bytes.Buffer
5488 r, _ := interp.New(interp.StdIO(nil, &b, &b))
5489 ctx, cancel := context.WithTimeout(t.Context(), runnerRunTimeout)
5490 defer cancel()
5491 for _, stmt := range file.Stmts {
5492 err := r.Run(ctx, stmt)
5493 if _, ok := errors.AsType[interp.ExitStatus](err); !ok && err != nil {
5494 // Keep track of unexpected errors.
5495 b.WriteString(err.Error())
5496 }
5497 if r.Exited() {
5498 break
5499 }
5500 }
5501 if got := b.String(); got != want {
5502 t.Fatalf("\nwant: %q\ngot: %q", want, got)
5503 }
5504 }
5505
5506 func TestRunnerIncrementalExitTrap(t *testing.T) {
5507 t.Parallel()
5508
5509 file := parse(t, nil, "trap 'echo bye' EXIT\necho a\necho b\nexit 3\necho never")
5510 want := "a\nb\nbye\n"
5511 var b bytes.Buffer
5512 r, _ := interp.New(interp.StdIO(nil, &b, &b))
5513 ctx, cancel := context.WithTimeout(t.Context(), runnerRunTimeout)
5514 defer cancel()
5515 var exit interp.ExitStatus
5516 for _, stmt := range file.Stmts {
5517 err := r.Run(ctx, stmt)
5518 if es, ok := errors.AsType[interp.ExitStatus](err); ok {
5519 exit = es
5520 } else if err != nil {
5521 b.WriteString(err.Error())
5522 }
5523 if r.Exited() {
5524 break
5525 }
5526 }
5527 if exit != 3 {
5528 t.Fatalf("want exit status 3, got %d", exit)
5529 }
5530 if got := b.String(); got != want {
5531 t.Fatalf("\nwant: %q\ngot: %q", want, got)
5532 }
5533 }
5534
5535 func TestRunnerResetFields(t *testing.T) {
5536 t.Parallel()
5537
5538 tdir := t.TempDir()
5539 logPath := filepath.Join(tdir, "log")
5540 logFile, err := os.Create(logPath)
5541 if err != nil {
5542 t.Fatal(err)
5543 }
5544 defer logFile.Close()
5545 r, _ := interp.New(
5546 interp.Params("-f", "--", "first", tdir, logPath),
5547 interp.Dir(tdir),
5548 interp.ExecHandlers(testExecHandler),
5549 )
5550 // Check that using option funcs and Runner fields directly is still
5551 // kept by Reset.
5552 interp.StdIO(nil, logFile, os.Stderr)(r)
5553 r.Env = expand.ListEnviron(append(os.Environ(), "GLOBAL=foo")...)
5554
5555 file := parse(t, nil, `
5556 # Params set 3 arguments
5557 [[ $# -eq 3 ]] || exit 10
5558 [[ $1 == "first" ]] || exit 11
5559
5560 # Params set the -f option (noglob)
5561 [[ -o noglob ]] || exit 12
5562
5563 # $PWD was set via Dir, and should be equal to $2
5564 [[ "$PWD" == "$2" ]] || exit 13
5565
5566 # stdout should go into the log file, which is at $3
5567 echo line1
5568 echo line2
5569 [[ "$(wc -l <$3)" == "2" ]] || exit 14
5570
5571 # $GLOBAL was set directly via the Env field
5572 [[ "$GLOBAL" == "foo" ]] || exit 15
5573
5574 # Change all of the above within the script. Reset should undo this.
5575 set +f -- newargs
5576 cd
5577 exec >/dev/null 2>/dev/null
5578 GLOBAL=
5579 export GLOBAL=
5580 `)
5581 ctx, cancel := context.WithTimeout(t.Context(), runnerRunTimeout)
5582 defer cancel()
5583 for i := range 3 {
5584 if err := r.Run(ctx, file); err != nil {
5585 t.Fatalf("run number %d: %v", i, err)
5586 }
5587 r.Reset()
5588 // empty the log file too
5589 logFile.Truncate(0)
5590 logFile.Seek(0, io.SeekStart)
5591 }
5592 }
5593
5594 func TestRunnerManyResets(t *testing.T) {
5595 t.Parallel()
5596 r, _ := interp.New()
5597 for range 5 {
5598 r.Reset()
5599 }
5600 }
5601
5602 func TestRunnerFilename(t *testing.T) {
5603 t.Parallel()
5604
5605 want := "f.sh\n"
5606 file, _ := syntax.NewParser().Parse(strings.NewReader("echo $0"), "f.sh")
5607 var b bytes.Buffer
5608 r, _ := interp.New(interp.StdIO(nil, &b, &b))
5609 ctx, cancel := context.WithTimeout(t.Context(), runnerRunTimeout)
5610 defer cancel()
5611 if err := r.Run(ctx, file); err != nil {
5612 t.Fatal(err)
5613 }
5614 if got := b.String(); got != want {
5615 t.Fatalf("\nwant: %q\ngot: %q", want, got)
5616 }
5617 }
5618
5619 func TestRunnerEnvNoModify(t *testing.T) {
5620 t.Parallel()
5621
5622 env := expand.ListEnviron("one=1", "two=2")
5623 file := parse(t, nil, `echo -n "$one $two; "; one=x; unset two`)
5624
5625 var b bytes.Buffer
5626 r, _ := interp.New(interp.Env(env), interp.StdIO(nil, &b, &b))
5627 ctx, cancel := context.WithTimeout(t.Context(), runnerRunTimeout)
5628 defer cancel()
5629 for range 3 {
5630 r.Reset()
5631 err := r.Run(ctx, file)
5632 if err != nil {
5633 t.Fatal(err)
5634 }
5635 }
5636
5637 want := "1 2; 1 2; 1 2; "
5638 if got := b.String(); got != want {
5639 t.Fatalf("\nwant: %q\ngot: %q", want, got)
5640 }
5641 }
5642
5643 func TestRunnerASTNoModify(t *testing.T) {
5644 t.Parallel()
5645
5646 file := parse(t, nil, "shopt -s expand_aliases; alias foo=echo\nfoo bar")
5647 printer := syntax.NewPrinter()
5648 var sb strings.Builder
5649 printer.Print(&sb, file)
5650 before := sb.String()
5651
5652 var b bytes.Buffer
5653 r, _ := interp.New(interp.StdIO(nil, &b, &b))
5654 ctx, cancel := context.WithTimeout(t.Context(), runnerRunTimeout)
5655 defer cancel()
5656 if err := r.Run(ctx, file); err != nil {
5657 t.Fatal(err)
5658 }
5659 if want := "bar\n"; b.String() != want {
5660 t.Fatalf("want output %q, got %q", want, b.String())
5661 }
5662
5663 sb.Reset()
5664 printer.Print(&sb, file)
5665 after := sb.String()
5666 if after != before {
5667 t.Fatalf("Run modified the AST:\nbefore: %q\nafter: %q", before, after)
5668 }
5669 }
5670
5671 func TestMalformedPathOnWindows(t *testing.T) {
5672 if runtime.GOOS != "windows" {
5673 t.Skip("Skipping windows test on non-windows GOOS")
5674 }
5675 tdir := t.TempDir()
5676 t.Parallel()
5677
5678 path := filepath.Join(tdir, "test.cmd")
5679 script := []byte("@echo foo")
5680 if err := os.WriteFile(path, script, 0o777); err != nil {
5681 t.Fatal(err)
5682 }
5683
5684 // set PATH to c:\tmp\dir instead of C:\tmp\dir
5685 volume := filepath.VolumeName(tdir)
5686 pathList := strings.ToLower(volume) + tdir[len(volume):]
5687
5688 file := parse(t, nil, "test.cmd")
5689 var cb concBuffer
5690 r, _ := interp.New(interp.Env(expand.ListEnviron("PATH="+pathList)), interp.StdIO(nil, &cb, &cb))
5691 ctx, cancel := context.WithTimeout(t.Context(), runnerRunTimeout)
5692 defer cancel()
5693 if err := r.Run(ctx, file); err != nil {
5694 t.Fatal(err)
5695 }
5696 want := "foo\r\n"
5697 if got := cb.String(); got != want {
5698 t.Fatalf("wrong output:\nwant: %q\ngot: %q", want, got)
5699 }
5700 }
5701
5702 func TestReadShouldNotPanicWithNilStdin(t *testing.T) {
5703 t.Parallel()
5704
5705 r, err := interp.New()
5706 if err != nil {
5707 t.Fatal(err)
5708 }
5709
5710 f := parse(t, nil, "read foobar")
5711 ctx, cancel := context.WithTimeout(t.Context(), runnerRunTimeout)
5712 defer cancel()
5713 if err := r.Run(ctx, f); err == nil {
5714 t.Fatal("it should have returned an error")
5715 }
5716 }
5717
5718 func TestRunnerVars(t *testing.T) {
5719 t.Parallel()
5720
5721 r, err := interp.New()
5722 if err != nil {
5723 t.Fatal(err)
5724 }
5725
5726 f := parse(t, nil, "foo=updated; BAR=new")
5727 ctx, cancel := context.WithTimeout(t.Context(), runnerRunTimeout)
5728 defer cancel()
5729 if err := r.Run(ctx, f); err != nil {
5730 t.Fatal(err)
5731 }
5732
5733 if want, got := "updated", r.Vars["foo"].String(); got != want {
5734 t.Fatalf("wrong output:\nwant: %q\ngot: %q", want, got)
5735 }
5736 }
5737
5738 func TestRunnerSubshell(t *testing.T) {
5739 t.Parallel()
5740
5741 r1, err := interp.New()
5742 if err != nil {
5743 t.Fatal(err)
5744 }
5745
5746 r2 := r1.Subshell()
5747 f1 := parse(t, nil, "PARENT=foo")
5748 f2 := parse(t, nil, "CHILD=bar")
5749
5750 ctx, cancel := context.WithTimeout(t.Context(), runnerRunTimeout)
5751 defer cancel()
5752 if err := r1.Run(ctx, f1); err != nil {
5753 t.Fatal(err)
5754 }
5755 if err := r2.Run(ctx, f2); err != nil {
5756 t.Fatal(err)
5757 }
5758
5759 if want, got := "foo", r1.Vars["PARENT"].String(); got != want {
5760 t.Fatalf("wrong output:\nwant: %q\ngot: %q", want, got)
5761 }
5762 if want, got := "bar", r2.Vars["CHILD"].String(); got != want {
5763 t.Fatalf("wrong output:\nwant: %q\ngot: %q", want, got)
5764 }
5765
5766 r3 := r2.Subshell()
5767 f3 := parse(t, nil, "CHILD=modified")
5768 if err := r3.Run(ctx, f3); err != nil {
5769 t.Fatal(err)
5770 }
5771 if want, got := "bar", r2.Vars["CHILD"].String(); got != want {
5772 t.Fatalf("wrong output:\nwant: %q\ngot: %q", want, got)
5773 }
5774 if want, got := "modified", r3.Vars["CHILD"].String(); got != want {
5775 t.Fatalf("wrong output:\nwant: %q\ngot: %q", want, got)
5776 }
5777 }
5778
5779 func TestRunnerNonFileStdin(t *testing.T) {
5780 const src = "while read a; do echo $a; GOSH_CMD=print_ok $GOSH_PROG; done"
5781 skipIfUnsupported(t, src)
5782 t.Parallel()
5783
5784 var cb concBuffer
5785 r, err := interp.New(interp.StdIO(strings.NewReader("a\nb\nc\n"), &cb, &cb))
5786 if err != nil {
5787 t.Fatal(err)
5788 }
5789 file := parse(t, nil, src)
5790 ctx, cancel := context.WithTimeout(t.Context(), runnerRunTimeout)
5791 defer cancel()
5792 if err := r.Run(ctx, file); err != nil {
5793 cb.WriteString(err.Error())
5794 }
5795 // TODO: just like with heredocs, the first print_ok call consumes all stdin.
5796 qt.Assert(t, qt.Equals(cb.String(), "a\nexec ok\nb\nexec ok\nc\nexec ok\n"))
5797 }