Debian Codegraph @

interp/interp_test.go

raw ◀ ▶
1 Debian patch touch this file
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 // Beware that macOS file systems are by default case-preserving but
2830 // case-insensitive, so e.g. "touch x X" creates only one file.
2831 "touch a ab Ac Ad; shopt -u nocaseglob; echo a*",
2832 "a ab\n",
2833 },
2834 {
2835 "touch a ab Ac Ad; shopt -s nocaseglob; echo a*",
2836 "Ac Ad a ab\n",
2837 },
2838 {
2839 "touch a ab abB Ac Ad; shopt -u nocaseglob; echo *b",
2840 "ab\n",
2841 },
2842 {
2843 "touch a ab abB Ac Ad; shopt -s nocaseglob; echo *b",
2844 "ab abB\n",
2845 },
2846 {
2847 "shopt -p",
2848 "shopt: unsupported option \"-p\"\nexit status 2 #IGNORE",
2849 },
2850 {
2851 "shopt -q",
2852 "shopt: unsupported option \"-q\"\nexit status 2 #IGNORE",
2853 },
2854
2855 // IFS
2856 {`echo -n "$IFS"`, " \t\n"},
2857 {`a="x:y:z"; IFS=:; echo $a`, "x y z\n"},
2858 {`a=(x y z); IFS=-; echo ${a[*]}`, "x y z\n"},
2859 {`a=(x y z); IFS=-; echo ${a[@]}`, "x y z\n"},
2860 {`a=(x y z); IFS=-; echo "${a[*]}"`, "x-y-z\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[*]}"`, "xyz\n"},
2864 {`a=(x y z); IFS=-; echo "${!a[@]}"`, "0 1 2\n"},
2865 {`set -- x y z; IFS=-; echo $*`, "x y z\n"},
2866 {`set -- x y z; IFS=-; echo "$*"`, "x-y-z\n"},
2867 {`set -- x y z; IFS=; echo $*`, "x y z\n"},
2868 {`set -- x y z; IFS=; echo "$*"`, "xyz\n"},
2869 {`set -- x y z; IFS=-; a=$*; echo "$a"`, "x-y-z\n"},
2870 {`set -- x y z; IFS=; a=$*; echo "$a"`, "xyz\n"},
2871 {`a=(x y z); IFS=; echo ${a[*]}; c=${a[*]}; echo "$c"`, "x y z\nxyz\n"},
2872 {`a=(x y z); IFS=-; b=${a[*]}; echo "$b"`, "x-y-z\n"},
2873 {`set -- x y; IFS=éz; a=$*; echo "$a"`, "xéy\n"},
2874 {`set -- xo yo; IFS=-; a=${*%o}; echo "$a"`, "x-y\n"},
2875 {`a=(zo wo); IFS=-; b=${a[*]^}; echo "$b"`, "Zo-Wo\n"},
2876 {`a=(x y z); IFS=-; echo "${!a[*]}"`, "0-1-2\n"},
2877 {`INTERP_Y_1=a INTERP_Y_2=b; IFS=-; echo "${!INTERP_Y_*}"`, "INTERP_Y_1-INTERP_Y_2\n"},
2878
2879 // builtin
2880 {"builtin", ""},
2881 {"builtin noexist", "exit status 1 #JUSTERR"},
2882 {"builtin echo foo", "foo\n"},
2883 {
2884 "echo() { printf 'bar\n'; }; echo foo; builtin echo foo",
2885 "bar\nfoo\n",
2886 },
2887
2888 // type
2889 {"type", ""},
2890 {"type for", "for is a shell keyword\n"},
2891 {"type echo", "echo is a shell builtin\n"},
2892 {"echo() { :; }; type echo | grep 'is a function'", "echo is a function\n"},
2893 {"type $PATH_PROG | grep -q -E ' is (/|[A-Z]:)'", ""},
2894 {"type noexist", "type: noexist: not found\nexit status 1 #JUSTERR"},
2895 {"type -o echo", "type: invalid option \"-o\"\nexit status 2 #JUSTERR"},
2896 {"PATH=/; type $PATH_PROG", "type: " + pathProg + ": not found\nexit status 1 #JUSTERR"},
2897 {"shopt -s expand_aliases; alias interp_foo='bar baz'\ntype interp_foo", "interp_foo is aliased to `bar baz'\n"},
2898 {"alias interp_foo='bar baz'\ntype interp_foo", "type: interp_foo: not found\nexit status 1 #JUSTERR"},
2899 {"type -p $PATH_PROG | grep -q -E '^(/|[A-Z]:)'", ""},
2900 {"PATH=/; type -p $PATH_PROG", "exit status 1"},
2901 // TODO: type -P should force PATH lookup even for builtins, unlike type -p.
2902 {"type -P $PATH_PROG | grep -q -E '^(/|[A-Z]:)'", ""},
2903 {"PATH=/; type -P $PATH_PROG", "exit status 1"},
2904 {"shopt -s expand_aliases; alias interp_foo='bar'; type -t interp_foo", "alias\n"},
2905 {"type -t case", "keyword\n"},
2906 {"interp_foo(){ :; }; type -t interp_foo", "function\n"},
2907 {"type -t type", "builtin\n"},
2908 {"type -t $PATH_PROG", "file\n"},
2909 {"type -t inexisting_dfgsdgfds", "exit status 1"},
2910
2911 // hash
2912 {"hash $PATH_PROG", ""},
2913
2914 // trap
2915 {"trap 'echo at_exit' EXIT; true", "at_exit\n"},
2916 {"trap 'echo on_err' ERR; false; echo FAIL", "on_err\nFAIL\n"},
2917 {"trap 'echo on_err' ERR; false || true; echo OK", "OK\n"},
2918 {"trap 'echo at_exit' EXIT; trap - EXIT; echo OK", "OK\n"},
2919 {"set -e; trap 'echo A' ERR EXIT; false; echo FAIL", "A\nA\nexit status 1"},
2920 {"trap 'foobar' UNKNOWN", "trap: UNKNOWN: invalid signal specification\nexit status 2 #JUSTERR"},
2921 // TODO: our builtin appears to not receive the piped bytes?
2922 // {"trap 'echo on_err' ERR; trap | grep -q '.*echo on_err.*'", "trap -- \"echo on_err\" ERR\n"},
2923 {"trap 'false' ERR EXIT; false", "exit status 1"},
2924 // A parse error in one trap callback must not disable later ones.
2925 {"trap '(' ERR; false; trap 'echo ok' ERR; false; :", "errortrap: error trap:1:1: `(` must be followed by a statement list\nok\n #IGNORE"},
2926 // On entry to a trap, "$?" is the status of the command which triggered it.
2927 {"trap 'echo err $?' ERR; false; echo after $?", "err 1\nafter 1\n"},
2928 {"trap 'echo exit $?' EXIT; false", "exit 1\nexit status 1"},
2929 {"trap 'echo exit $?' EXIT; true", "exit 0\n"},
2930 {"trap 'false; echo next $?' EXIT; true", "next 1\n"},
2931 {"trap 'echo err $?' ERR; trap 'echo exit $?' EXIT; false; true", "err 1\nexit 0\n"},
2932 {"false; trap 'echo exit $?' EXIT; true", "exit 0\n"},
2933
2934 // eval
2935 {"eval", ""},
2936 {"eval ''", ""},
2937 {"eval echo foo", "foo\n"},
2938 {"eval 'echo foo'", "foo\n"},
2939 {"eval 'exit 1'", "exit status 1"},
2940 {"eval '(x'", "eval: 1:1: reached EOF without matching `(` with `)`\nexit status 1 #JUSTERR"},
2941 {"set a b; eval 'echo $@'", "a b\n"},
2942 {"eval 'a=foo'; echo $a", "foo\n"},
2943 {`a=b eval "echo $a"`, "\n"},
2944 {`a=b eval 'echo $a'`, "b\n"},
2945 {`eval 'echo "\$a"'`, "$a\n"},
2946 {`a=b eval 'x=y eval "echo \$a \$x"'`, "b y\n"},
2947 {`a=b eval 'a=y eval "echo $a \$a"'`, "b y\n"},
2948 {"a=b eval '(echo $a)'", "b\n"},
2949
2950 // source
2951 {
2952 "source",
2953 "1:1: source: need filename\nexit status 2 #JUSTERR",
2954 },
2955 {
2956 "echo 'echo foo' >a; source ./a; . ./a",
2957 "foo\nfoo\n",
2958 },
2959 {
2960 "echo 'echo $@' >a; source ./a; source ./a b c; echo $@",
2961 "\nb c\n\n",
2962 },
2963 {
2964 "echo 'foo=bar' >a; source ./a; echo $foo",
2965 "bar\n",
2966 },
2967
2968 // source from PATH
2969 {
2970 "mkdir test; echo 'echo foo' >test/a; PATH=$PWD/test source a; . test/a",
2971 "foo\nfoo\n",
2972 },
2973
2974 // source with set and shift
2975 {
2976 "echo 'set -- d e f' >a; source ./a; echo $@",
2977 "d e f\n",
2978 },
2979 {
2980 "echo 'echo $@' >a; set -- b c; source ./a; echo $@",
2981 "b c\nb c\n",
2982 },
2983 {
2984 "echo 'echo $@' >a; set -- b c; source ./a d e; echo $@",
2985 "d e\nb c\n",
2986 },
2987 {
2988 "echo 'shift; echo $@' >a; set -- b c; source ./a d e; echo $@",
2989 "e\nb c\n",
2990 },
2991 {
2992 "echo 'shift' >a; set -- b c; source ./a; echo $@",
2993 "c\n",
2994 },
2995 {
2996 "echo 'shift; set -- $@' >a; set -- b c; source ./a d e; echo $@",
2997 "e\n",
2998 },
2999 {
3000 "echo 'set -- g f'>b; echo 'set -- d e f; echo $@; source ./b;' >a; source ./a; echo $@",
3001 "d e f\ng f\n",
3002 },
3003 {
3004 "echo 'set -- g f'>b; echo 'echo $@; set -- d e f; source ./b;' >a; source ./a b c; echo $@",
3005 "b c\ng f\n",
3006 },
3007 {
3008 "echo 'shift; echo $@' >b; echo 'shift; echo $@; source ./b' >a; source ./a b c d; echo $@",
3009 "c d\nd\n\n",
3010 },
3011 {
3012 "echo 'set -- b c d' >b; echo 'source ./b' >a; set -- a; source ./a; echo $@",
3013 "b c d\n",
3014 },
3015 {
3016 "echo 'echo $@' >b; echo 'set -- b c d; source ./b' >a; set -- a; source ./a; echo $@",
3017 "b c d\nb c d\n",
3018 },
3019 {
3020 "echo 'shift; echo $@' >b; echo 'shift; echo $@; source ./b c d' >a; set -- a b; source ./a; echo $@",
3021 "b\nd\nb\n",
3022 },
3023 {
3024 "echo 'set -- a b c' >b; echo 'echo $@; source ./b; echo $@' >a; source ./a; echo $@",
3025 "\na b c\na b c\n",
3026 },
3027
3028 // indexed arrays
3029 {
3030 "a=foo; echo ${a[0]} ${a[@]} ${a[x]}; echo ${a[1]}",
3031 "foo foo foo\n\n",
3032 },
3033 {
3034 "a=(); echo ${a[0]} ${a[@]} ${a[x]} ${a[1]}",
3035 "\n",
3036 },
3037 {
3038 "a=(b c); echo $a; echo ${a[0]}; echo ${a[1]}; echo ${a[x]}",
3039 "b\nb\nc\nb\n",
3040 },
3041 {
3042 "a=(b c); echo ${a[@]}; echo ${a[*]}",
3043 "b c\nb c\n",
3044 },
3045 {
3046 "a=(1 2 3); echo ${a[2-1]}; echo $((a[1+1]))",
3047 "2\n3\n",
3048 },
3049 {
3050 "a=(1 2) x=(); a+=b x+=c; echo ${a[@]}; echo ${x[@]}",
3051 "1b 2\nc\n",
3052 },
3053 {
3054 "a=(1 2) x=(); a+=(b c) x+=(d e); echo ${a[@]}; echo ${x[@]}",
3055 "1 2 b c\nd e\n",
3056 },
3057 {
3058 "a=bbb; a+=(c d); echo ${a[@]}",
3059 "bbb c d\n",
3060 },
3061 {
3062 `a=('a 1' 'b 2'); for e in ${a[@]}; do echo "$e"; done`,
3063 "a\n1\nb\n2\n",
3064 },
3065 {
3066 `a=('a 1' 'b 2'); for e in "${a[*]}"; do echo "$e"; done`,
3067 "a 1 b 2\n",
3068 },
3069 {
3070 `a=('a 1' 'b 2'); for e in "${a[@]}"; do echo "$e"; done`,
3071 "a 1\nb 2\n",
3072 },
3073 {
3074 `declare -a a; a[0]='a 1'; a[1]='b 2'; for e in "${a[@]}"; do echo "$e"; done`,
3075 "a 1\nb 2\n",
3076 },
3077 {
3078 `a=([1]=y [0]=x); echo ${a[0]}`,
3079 "x\n",
3080 },
3081 {
3082 `a=(y); a[2]=x; echo ${a[2]}`,
3083 "x\n",
3084 },
3085 {
3086 `a="y"; a[2]=x; echo ${a[2]}`,
3087 "x\n",
3088 },
3089 {
3090 `declare -a a=(x y); echo ${a[1]}`,
3091 "y\n",
3092 },
3093 {
3094 `a=b; echo "${a[@]}"`,
3095 "b\n",
3096 },
3097 {
3098 `a=(b); echo ${a[3]}`,
3099 "\n",
3100 },
3101 {
3102 `a=(b); echo ${a[-2]}`,
3103 "negative array index\n #JUSTERR",
3104 },
3105 // TODO: also test with gaps in arrays.
3106 {
3107 `a=([0]=' x ' [1]=' y '); for v in "${a[@]}"; do echo "$v"; done`,
3108 " x \n y \n",
3109 },
3110 {
3111 `a=([0]=' x ' [1]=' y '); for v in "${a[*]}"; do echo "$v"; done`,
3112 " x y \n",
3113 },
3114 {
3115 `a=([0]=' x ' [1]=' y '); for v in "${!a[@]}"; do echo "$v"; done`,
3116 "0\n1\n",
3117 },
3118 {
3119 `a=([0]=' x ' [1]=' y '); for v in "${!a[*]}"; do echo "$v"; done`,
3120 "0 1\n",
3121 },
3122
3123 // associative arrays
3124 {
3125 `a=foo; echo ${a[""]} ${a["x"]}`,
3126 "foo foo\n",
3127 },
3128 {
3129 `declare -A a=(); echo ${a[0]} ${a[@]} ${a[1]} ${a["x"]}`,
3130 "\n",
3131 },
3132 {
3133 `declare -A a=([x]=b [y]=c); echo $a; echo ${a[0]}; echo ${a["x"]}; echo ${a["_"]}`,
3134 "\n\nb\n\n",
3135 },
3136 {
3137 `declare -Ag a=([x]=y); echo ${a["x"]}`,
3138 "y\n",
3139 },
3140 {
3141 `declare -A a=([x]=b [y]=c); for e in ${a[@]}; do echo $e; done | sort`,
3142 "b\nc\n",
3143 },
3144 {
3145 `declare -A a=([y]=b [x]=c); for e in ${a[*]}; do echo $e; done | sort`,
3146 "b\nc\n",
3147 },
3148 {
3149 `declare -A a=([x]=a); a["y"]=d; a["x"]=c; for e in ${a[@]}; do echo $e; done | sort`,
3150 "c\nd\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 // cheating a little; bash just did a=c
3158 `a=(["x"]=b ["y"]=c); echo ${a["y"]}`,
3159 "c\n",
3160 },
3161 {
3162 `declare -A a=(['x']=b); echo ${a['x']} ${a[$'x']} ${a[$"x"]}`,
3163 "b b b\n",
3164 },
3165 {
3166 `a=(['x']=b); echo ${a['y']}`,
3167 "\n #IGNORE bash requires -A",
3168 },
3169 {
3170 `declare -A a=(['a 1']=' x ' ['b 2']=' y '); for v in "${a[@]}"; do echo "$v"; done | sort`,
3171 " x \n y \n",
3172 },
3173 {
3174 `declare -A a=(['a 1']=' x ' ['b 2']=' y '); for v in "${a[*]}"; do echo "$v"; done`,
3175 " x y \n",
3176 },
3177 {
3178 `declare -A a=(['a 1']=' x ' ['b 2']=' y '); for v in "${!a[@]}"; do echo "$v"; done | sort`,
3179 "a 1\nb 2\n",
3180 },
3181 {
3182 `declare -A a=(['a 1']=' x ' ['b 2']=' y '); for v in "${!a[*]}"; do echo "$v"; done`,
3183 "a 1 b 2\n",
3184 },
3185 {
3186 `declare -A a; a[a]=x; a[b]=y; for v in "${!a[@]}"; do echo "$v"; done | sort`,
3187 "a\nb\n",
3188 },
3189 {
3190 `declare -A a; a[a]=x; a[b]=y; declare -A a; for v in "${!a[@]}"; do echo "$v"; done | sort`,
3191 "a\nb\n",
3192 },
3193 // weird assignments
3194 {"a=b; a=(c d); echo ${a[@]}", "c d\n"},
3195 {"a=(b c); a=d; echo ${a[@]}", "d c\n"},
3196 {"declare -A a=([x]=b [y]=c); a=d; for e in ${a[@]}; do echo $e; done | sort", "b\nc\nd\n"},
3197 {"i=3; a=b; a[i]=x; echo ${a[@]}", "b x\n"},
3198 {"i=3; declare a=(b); a[i]=x; echo ${!a[@]}", "0 3\n"},
3199 {`a=(x "" y); echo ${!a[@]}; echo "${!a[@]}"`, "0 1 2\n0 1 2\n"},
3200 {"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"},
3201 {"i=3; declare -A a=(['x']=b); a[i]=x; for e in ${!a[@]}; do echo $e; done | sort", "i\nx\n"},
3202
3203 // sparse indexed arrays
3204 {"a[5]=x; echo ${#a[@]} ${a[@]} ${!a[@]}", "1 x 5\n"},
3205 {"a=([5]=x [2]=y); echo ${!a[@]}; echo ${a[@]}", "2 5\ny x\n"},
3206 {"a=([5]=x y z); echo ${!a[@]}", "5 6 7\n"},
3207 {"a[5]=x; a[2]=y; declare -p a", "declare -a a=([2]=\"y\" [5]=\"x\")\n"},
3208 {"a[5]=x; echo ${a[0]-unset} ${a[5]}; echo \"${a[@]}\"", "unset x\nx\n"},
3209 {"a=(x y z); unset 'a[1]'; echo ${#a[@]} ${!a[@]} ${a[@]}", "2 0 2 x z\n"},
3210 {"a=(x y z); unset 'a[2]'; echo ${#a[@]} ${!a[@]} ${a[@]}", "2 0 1 x y\n"},
3211 {"a=(x y z); unset 'a[1]'; a+=(w); echo ${!a[@]}", "0 2 3\n"},
3212 {"a=(x y z); unset 'a[@]'; echo ${#a[@]}", "0\n"},
3213 {"a=(w x y z); i=2; unset \"a[i+1]\"; echo ${!a[@]}", "0 1 2\n"},
3214 {"declare -A a=([x]=1 [y]=2); unset 'a[x]'; echo ${!a[@]}", "y\n"},
3215 {"a=(1 2 3); a[-1]=x; echo ${a[@]}", "1 2 x\n"},
3216 {"a=(x); a+=([5]=z w); echo ${!a[@]}; echo ${a[@]}", "0 5 6\nx z w\n"},
3217 {"a=s; a+=([0]=x); echo ${a[@]}", "x\n"},
3218 {"a=([5]=x); a+=s; echo ${!a[@]}; echo ${a[@]}", "0 5\ns x\n"},
3219 {"a=([1]=one [5]=five [10]=ten); echo ${a[@]:2:2}; echo ${a[@]:5}; echo ${a[@]: -1}", "five ten\nfive ten\nten\n"},
3220 {"a=([2]=x [5]=y); echo \"${a[@]::1}\" \"${a[@]:0}\"", "x x y\n"},
3221 {"a=([2]=x [5]=y); echo $a ${a[0]-unset}", "unset\n"},
3222 {"a=([0]=x [5]=y); echo $a", "x\n"},
3223 {"a=([5]=x); echo ${a+set} ${a-unset}", "unset\n"},
3224 {"a=(x y); : \"${a[5]=z}\"; declare -p a", "declare -a a=([0]=\"x\" [1]=\"y\" [5]=\"z\")\n"},
3225 {"s=x; : \"${s[1]=z}\"; declare -p s", "declare -a s=([0]=\"x\" [1]=\"z\")\n"},
3226 {"declare -A m=([k]=v); : \"${m[j]=z}\"; echo ${m[j]} ${m[k]}", "z v\n"},
3227 {"a=([5]=b [-1]=c d); declare -p a", "declare -a a=([5]=\"c\" [6]=\"d\")\n"},
3228 {"a=(1 2 3); echo ${a[-1]} ${a[-3]}", "3 1\n"},
3229 {"a=(x); unset 'a[]'; echo $?; declare -p a", "0\ndeclare -a a=([0]=\"x\")\n"},
3230 {"s=x; unset 's[0]'; echo ${s-unset}", "unset\n"},
3231 {"s=x; unset 's[5]'; echo $s", "unset: s: not an array variable\nx\n #JUSTERR"},
3232 {"a=([5]=x); (a[2]=y; echo ${!a[@]}); echo ${!a[@]}", "2 5\n5\n"},
3233 {"a=([1]=y [0]=x); declare -p a", "declare -a a=([0]=\"x\" [1]=\"y\")\n"},
3234 {"declare -n r=a; a=(1 2 3); unset 'r[1]'; echo ${!a[@]}", "0 2\n"},
3235
3236 // declare
3237 {"declare -B foo", "declare: invalid option \"-B\"\nexit status 2 #JUSTERR"},
3238 {"a=b; declare a; echo $a; declare a=; echo $a", "b\n\n"},
3239 {"a=b; declare a; echo $a", "b\n"},
3240 {
3241 "declare a=b c=(1 2); echo $a; echo ${c[@]}",
3242 "b\n1 2\n",
3243 },
3244 {"a=x; declare $a; echo $a $x", "x\n"},
3245 {"a=x=y; declare $a; echo $a $x", "x=y y\n"},
3246 {"a='x=(y)'; declare $a; echo $a $x", "x=(y) (y)\n"},
3247 {"a='x=b y=c'; declare $a; echo $x $y", "b c\n"},
3248 {"declare =bar", "declare: invalid name \"\"\nexit status 1 #JUSTERR"},
3249 {"declare $unset=$unset", "declare: invalid name \"\"\nexit status 1 #JUSTERR"},
3250
3251 // export
3252 {"declare foo=bar; $ENV_PROG | grep '^foo='", "exit status 1"},
3253 {"declare -x foo=bar; $ENV_PROG | grep '^foo='", "foo=bar\n"},
3254 {"export foo=bar; $ENV_PROG | grep '^foo='", "foo=bar\n"},
3255 {"foo=bar; export foo; $ENV_PROG | grep '^foo='", "foo=bar\n"},
3256 {"export foo=bar; foo=baz; $ENV_PROG | grep '^foo='", "foo=baz\n"},
3257 {"export foo=bar; readonly foo=baz; $ENV_PROG | grep '^foo='", "foo=baz\n"},
3258 {"export foo=(1 2); $ENV_PROG | grep '^foo='", "exit status 1"},
3259 {"declare -A foo=([a]=b); export foo; $ENV_PROG | grep '^foo='", "exit status 1"},
3260 {"export foo=(b c); foo=x; $ENV_PROG | grep '^foo='", "exit status 1"},
3261 {"foo() { bar=foo; export bar; }; foo; $ENV_PROG | grep ^bar=", "bar=foo\n"},
3262 {"foo() { export bar; }; bar=foo; foo; $ENV_PROG | grep ^bar=", "bar=foo\n"},
3263 {"foo() { export bar; }; foo; bar=foo; $ENV_PROG | grep ^bar=", "bar=foo\n"},
3264 {"foo() { export bar=foo; }; foo; readonly bar; $ENV_PROG | grep ^bar=", "bar=foo\n"},
3265
3266 // local
3267 {
3268 "local a=b",
3269 "local: can only be used in a function\nexit status 1 #JUSTERR",
3270 },
3271 {
3272 "local a=b 2>/dev/null; echo $a",
3273 "\n",
3274 },
3275 {
3276 "{ local a=b; }",
3277 "local: can only be used in a function\nexit status 1 #JUSTERR",
3278 },
3279 {
3280 "echo 'local a=b' >a; source ./a",
3281 "local: can only be used in a function\nexit status 1 #JUSTERR",
3282 },
3283 {
3284 "echo 'local a=b' >a; f() { source ./a; }; f; echo $a",
3285 "\n",
3286 },
3287 {
3288 "f() { local a=b; }; f; echo $a",
3289 "\n",
3290 },
3291 {
3292 "a=x; f() { local a=b; }; f; echo $a",
3293 "x\n",
3294 },
3295 {
3296 "a=x; f() { echo $a; local a=b; echo $a; }; f",
3297 "x\nb\n",
3298 },
3299 {
3300 "f1() { local a=b; }; f2() { f1; echo $a; }; f2",
3301 "\n",
3302 },
3303 {
3304 "f() { a=1; declare b=2; export c=3; readonly d=4; declare -g e=5; }; f; echo $a $b $c $d $e",
3305 "1 3 4 5\n",
3306 },
3307 {
3308 `f() { local x; [[ -v x ]] && echo set || echo unset; }; f`,
3309 "unset\n",
3310 },
3311 {
3312 `f() { local x=; [[ -v x ]] && echo set || echo unset; }; f`,
3313 "set\n",
3314 },
3315 {
3316 `export x=before; f() { local x; export x=after; $ENV_PROG | grep '^x='; }; f; echo $x`,
3317 "x=after\nbefore\n",
3318 },
3319 {
3320 "getx() { echo $X; }; f() { local X=Y; getx; echo $X; }; f",
3321 "Y\nY\n",
3322 },
3323 {
3324 "setx() { X=Y; }; f() { local X; setx; echo $X; }; f",
3325 "Y\n",
3326 },
3327 {
3328 "setx() { local X=Y; }; f() { local X; setx; echo $X; }; f",
3329 "\n",
3330 },
3331 {
3332 "setx() { declare X=Y; }; f() { local X; setx; echo $X; }; f",
3333 "\n",
3334 },
3335 {
3336 "setx() { X=Y :; }; f() { local X; setx; echo $X; }; f",
3337 "\n",
3338 },
3339
3340 // unset global from inside function
3341 {"f() { unset foo; echo $foo; }; foo=bar; f", "\n"},
3342 {"f() { unset foo; }; foo=bar; f; echo $foo", "\n"},
3343
3344 // name references
3345 {"declare -n foo=bar; bar=etc; [[ -R foo ]]", ""},
3346 {"declare -n foo=bar; bar=etc; [ -R foo ]", ""},
3347 {"nameref foo=bar; bar=etc; [[ -R foo ]]", " #IGNORE"},
3348 {"declare foo=bar; bar=etc; [[ -R foo ]]", "exit status 1"},
3349 {
3350 "declare -n foo=bar; bar=etc; echo $foo; bar=zzz; echo $foo",
3351 "etc\nzzz\n",
3352 },
3353 {
3354 "declare -n foo=bar; bar=(x y); echo ${foo[1]}; bar=(a b); echo ${foo[1]}",
3355 "y\nb\n",
3356 },
3357 {
3358 "declare -n foo=bar; bar=etc; echo $foo; unset bar; echo $foo",
3359 "etc\n\n",
3360 },
3361 {
3362 "declare -n a1=a2 a2=a3 a3=a4; a4=x; echo $a1 $a3",
3363 "x x\n",
3364 },
3365 {
3366 "declare -n foo=bar bar=foo; echo $foo",
3367 "\n #IGNORE",
3368 },
3369 {
3370 "declare -n foo=bar; echo $foo",
3371 "\n",
3372 },
3373 {
3374 "declare -n foo=bar; echo ${!foo}",
3375 "bar\n",
3376 },
3377 {
3378 "declare -n foo=bar; bar=etc; echo $foo; echo ${!foo}",
3379 "etc\nbar\n",
3380 },
3381 {
3382 "declare -n foo=bar; bar=etc; foo=value; echo $foo; echo $bar",
3383 "value\nvalue\n",
3384 },
3385 {
3386 "declare -n foo=bar; foo=value; echo $foo; echo $bar",
3387 "value\nvalue\n",
3388 },
3389 {
3390 "declare -n foo=bar; declare foo=value; echo $foo; echo $bar",
3391 "value\nvalue\n",
3392 },
3393 {
3394 "declare -n foo=bar bar=baz; foo=value; echo $foo; echo $bar; echo $baz",
3395 "value\nvalue\nvalue\n",
3396 },
3397 {
3398 "declare -n foo=bar; set -u; echo ${foo}",
3399 "foo: unbound variable\nexit status 1 #JUSTERR",
3400 },
3401 {
3402 "declare -n foo=bar; set -u; echo ${foo:=value}; echo $foo; echo $bar",
3403 "value\nvalue\nvalue\n",
3404 },
3405 {
3406 "declare -n foo=bar; foo=value $ENV_PROG | grep '^bar='",
3407 "bar=value\n",
3408 },
3409 {
3410 "echo ${!@}-${!*}; set -- foo; echo ${!@}-${!*}-${!1}; foo=value; echo ${!@}-${!*}-${!1}",
3411 "-\n--\nvalue-value-value\n",
3412 },
3413 {
3414 "declare -n ref=arr; ref+=(x y); echo ${ref[@]} ${arr[@]}",
3415 "x y x y\n",
3416 },
3417
3418 // read-only vars
3419 {"declare -r foo=bar; echo $foo", "bar\n"},
3420 {"readonly foo=bar; echo $foo", "bar\n"},
3421 {"readonly foo=bar; export foo; echo $foo", "bar\n"},
3422 {"readonly foo=bar; readonly bar=foo; export foo bar; echo $bar", "foo\n"},
3423 {
3424 "a=b; a=c; echo $a; readonly a; a=d",
3425 "c\na: readonly variable\nexit status 1 #JUSTERR",
3426 },
3427 {
3428 "declare -r foo=bar; foo=etc",
3429 "foo: readonly variable\nexit status 1 #JUSTERR",
3430 },
3431 {
3432 "declare -r foo=bar; export foo=",
3433 "foo: readonly variable\nexit status 1 #JUSTERR",
3434 },
3435 {
3436 "readonly foo=bar; foo=etc",
3437 "foo: readonly variable\nexit status 1 #JUSTERR",
3438 },
3439 {
3440 "foo() { bar=foo; readonly bar; }; foo; bar=bar",
3441 "bar: readonly variable\nexit status 1 #JUSTERR",
3442 },
3443 {
3444 "foo() { readonly bar; }; foo; bar=foo",
3445 "bar: readonly variable\nexit status 1 #JUSTERR",
3446 },
3447 {
3448 "foo() { readonly bar=foo; }; foo; export bar; $ENV_PROG | grep '^bar='",
3449 "bar=foo\n",
3450 },
3451
3452 // multiple var modes at once
3453 {
3454 "declare -r -x foo=bar; $ENV_PROG | grep '^foo='",
3455 "foo=bar\n",
3456 },
3457 {
3458 "declare -r -x foo=bar; foo=x",
3459 "foo: readonly variable\nexit status 1 #JUSTERR",
3460 },
3461
3462 // globbing
3463 {"echo .", ".\n"},
3464 {"echo ..", "..\n"},
3465 {"echo ./.", "./.\n"},
3466 {
3467 ">a.x >b.x >c.x; echo *.x; rm a.x b.x c.x",
3468 "a.x b.x c.x\n",
3469 },
3470 {
3471 `>a.x; echo '*.x' "*.x"; rm a.x`,
3472 "*.x *.x\n",
3473 },
3474 {
3475 `>a.x >b.y; echo *'.'x; rm a.x`,
3476 "a.x\n",
3477 },
3478 {
3479 `>a.x; echo *'.x' "a."* '*'.x; rm a.x`,
3480 "a.x a.x *.x\n",
3481 },
3482 {
3483 "echo *.x; echo foo *.y bar",
3484 "*.x\nfoo *.y bar\n",
3485 },
3486 {
3487 `>a.x >b.x >c.x; a=*.x; echo $a; echo "$a"`,
3488 "a.x b.x c.x\n*.x\n",
3489 },
3490 {
3491 `>a.x >b.x >c.x; a=(*.x); echo "${a[@]}"; echo ${a[1]}`,
3492 "a.x b.x c.x\nb.x\n",
3493 },
3494 {
3495 "mkdir a; >a/b.x; echo */*.x | sed 's@\\\\@/@g'; cd a; echo *.x",
3496 "a/b.x\nb.x\n",
3497 },
3498 {
3499 "mkdir -p a/b/c; echo a/* | sed 's@\\\\@/@g'",
3500 "a/b\n",
3501 },
3502 {
3503 ">.hidden >a; echo *; echo .h*; rm .hidden a",
3504 "a\n.hidden\n",
3505 },
3506 {
3507 `mkdir d; >d/.hidden >d/a; set -- "$(echo d/*)" "$(echo d/.h*)"; echo ${#1} ${#2}; rm -r d`,
3508 "3 9\n",
3509 },
3510 {
3511 "mkdir -p a/b/c; echo a/** | sed 's@\\\\@/@g'",
3512 "a/b\n",
3513 },
3514 {
3515 "shopt -s globstar; mkdir -p a/b/c; echo a/** | sed 's@\\\\@/@g'",
3516 "a/ a/b a/b/c\n",
3517 },
3518 {
3519 "shopt -s globstar; mkdir -p a/b/c; echo **/c | sed 's@\\\\@/@g'",
3520 "a/b/c\n",
3521 },
3522 {
3523 "shopt -s globstar; mkdir -p a/b; touch c; echo ** | sed 's@\\\\@/@g'",
3524 "a a/b c\n",
3525 },
3526 {
3527 "shopt -s globstar; mkdir -p a/b; touch c; echo **/ | sed 's@\\\\@/@g'",
3528 "a/ a/b/\n",
3529 },
3530 {
3531 "shopt -s globstar; mkdir -p a/b/c a/d; echo ** | sed 's@\\\\@/@g'",
3532 "a a/b a/b/c a/d\n",
3533 },
3534 {
3535 "shopt -s globstar; mkdir -p a.x a/b.x a/b/c.x; echo **.x ./**.x | sed 's@\\\\@/@g'",
3536 "a.x ./a.x\n",
3537 },
3538 {
3539 "shopt -s globstar; mkdir -p a/b; touch a/b/c; echo **/* | sed 's@\\\\@/@g'",
3540 "a a/b a/b/c\n",
3541 },
3542 {
3543 "shopt -s globstar; mkdir -p b; touch x2 a b/c d x1; echo **/* | sed 's@\\\\@/@g'",
3544 "a b b/c d x1 x2\n",
3545 },
3546 {
3547 "mkdir foo; touch foo/bar; echo */bar */bar/ | sed 's@\\\\@/@g'",
3548 "foo/bar */bar/\n",
3549 },
3550 {
3551 "shopt -s nullglob; touch existing-1; echo missing-* existing-*",
3552 "existing-1\n",
3553 },
3554 {
3555 "touch ŀfoo; echo ŀ*",
3556 "ŀfoo\n",
3557 },
3558
3559 // Extended globbing via the extglob option.
3560 // Note how extglob affects Bash's own line-by-line parsing, so we set the option before a newline.
3561 {
3562 "shopt -s extglob\necho invalid-?([)",
3563 "invalid-?([)\n",
3564 },
3565 {
3566 "touch az a1z a12z a123z; echo a?([0-9])z",
3567 "extended globbing operator used without the \"extglob\" option set\n #JUSTERR",
3568 },
3569 {
3570 "shopt -s extglob\ntouch az a1z a12z a123z; echo a?([0-9])z",
3571 "a1z az\n",
3572 },
3573 {
3574 "shopt -s extglob\ntouch az a1z a12z a123z; echo a*([0-9])z",
3575 "a123z a12z a1z az\n",
3576 },
3577 {
3578 "shopt -s extglob\ntouch az a1z a12z a123z; echo a+([0-9])z",
3579 "a123z a12z a1z\n",
3580 },
3581 {
3582 "shopt -s extglob\ntouch az a1z a12z a123z; echo a@([0-9])z",
3583 "a1z\n",
3584 },
3585 {
3586 "shopt -s extglob\ntouch a{1..9}0z; echo a+(0|[1-2]|8)z",
3587 "a10z a20z a80z\n",
3588 },
3589 {
3590 "shopt -s extglob\ntouch az a1z a12z a123z; echo a!([0-9])z",
3591 "a123z a12z az\n",
3592 },
3593 // !(pattern) extglob negation in case and [[ ]] matching
3594 {
3595 "shopt -s extglob\ncase \"bar\" in !(foo)) echo match;; esac",
3596 "match\n",
3597 },
3598 {
3599 "shopt -s extglob\ncase \"foo\" in !(foo)) echo match;; esac",
3600 "",
3601 },
3602 {
3603 "shopt -s extglob\ncase \"\" in !(foo)) echo match;; esac",
3604 "match\n",
3605 },
3606 {
3607 "shopt -s extglob\ncase \"baz\" in !(foo|bar)) echo match;; esac",
3608 "match\n",
3609 },
3610 {
3611 "shopt -s extglob\ncase \"file.tar.gz\" in !(*.sig)) echo match;; esac",
3612 "match\n",
3613 },
3614 {
3615 "shopt -s extglob\ncase \"file.sig\" in !(*.sig)) echo match;; esac",
3616 "",
3617 },
3618 {
3619 "shopt -s extglob\ncase \"foo_xxx_baz\" in foo_!(bar)_baz) echo match;; esac",
3620 "match\n",
3621 },
3622 {
3623 "shopt -s extglob\ncase \"foo_bar_baz\" in foo_!(bar)_baz) echo match;; esac",
3624 "",
3625 },
3626 {
3627 "shopt -s extglob\n[[ \"bar\" == !(foo) ]] && echo match",
3628 "match\n",
3629 },
3630 // Unsupported: multiple groups, glob prefix, or glob suffix.
3631 {
3632 "shopt -s extglob\ncase \"xabab\" in *a!(b)) echo match;; esac",
3633 "extglob !(...) is only supported with a fixed prefix and suffix\n #IGNORE glob prefix not supported",
3634 },
3635 {
3636 "shopt -s extglob\ncase \"baz\" in !(foo)!(bar)) echo match;; esac",
3637 "multiple extglob !(...) groups are not supported yet\n #IGNORE multiple extglob negation groups not supported",
3638 },
3639 {
3640 "shopt -s extglob\ncase \".bar\" in .*!(foo)) echo match;; esac",
3641 "extglob !(...) is only supported with a fixed prefix and suffix\n #IGNORE glob prefix not supported",
3642 },
3643 {
3644 "shopt -s extglob\ncase \".foo\" 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 \"bar\" 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 // Extended pattern matching is always available outside of pathname expansions (globbing).
3653 "[[ a123z == a@([0-9])z ]]; echo $?; [[ a123z == a+([0-9])z ]]; echo $?",
3654 "1\n0\n",
3655 },
3656 // Ensure that setting nullglob does not return invalid globs as null
3657 // strings.
3658 {
3659 "shopt -s nullglob; [ -n butter ] && echo bubbles",
3660 "bubbles\n",
3661 },
3662 {
3663 "cat <<EOF\n{foo,bar}\nEOF",
3664 "{foo,bar}\n",
3665 },
3666 {
3667 "cat <<EOF\n*.go\nEOF",
3668 "*.go\n",
3669 },
3670 {
3671 "mkdir -p a/b a/c; echo ./a/* | sed 's@\\\\@/@g'",
3672 "./a/b ./a/c\n",
3673 },
3674 {
3675 "mkdir -p a/b a/c d; cd d; echo ../a/* | sed 's@\\\\@/@g'",
3676 "../a/b ../a/c\n",
3677 },
3678 {
3679 "mkdir x-d1 x-d2; >x-f; echo x-*/ | sed 's@\\\\@/@g'",
3680 "x-d1/ x-d2/\n",
3681 },
3682 {
3683 "mkdir x-d1 x-d2; >x-f; echo ././x-*/// | sed 's@\\\\@/@g'",
3684 "././x-d1/ ././x-d2/\n",
3685 },
3686 {
3687 "mkdir -p x-d1/a x-d2/b; >x-f; echo x-*/* | sed 's@\\\\@/@g'",
3688 "x-d1/a x-d2/b\n",
3689 },
3690 {
3691 "mkdir -p foo/bar; ln -s foo sym; echo sy*/; echo sym/b*",
3692 "sym/\nsym/bar\n",
3693 },
3694 {
3695 ">foo; ln -s foo sym; echo sy*; echo sy*/",
3696 "sym\nsy*/\n",
3697 },
3698 {
3699 "mkdir x-d; >x-f; test -d $PWD/x-*/",
3700 "",
3701 },
3702 {
3703 "mkdir dir; >dir/x-f; ln -s dir sym; cd sym; test -f $PWD/x-*",
3704 "",
3705 },
3706
3707 // brace expansion; there are also some tests in the expand package
3708 {"echo a}b", "a}b\n"},
3709 {"echo {a,b{c,d}", "{a,bc {a,bd\n"},
3710 {"echo a{b}", "a{b}\n"},
3711 {"echo a{à,世界}", "aà a世界\n"},
3712 {"echo a{b,c}d{e,f}g", "abdeg abdfg acdeg acdfg\n"},
3713 {"echo a{b{x,y},c}d", "abxd abyd acd\n"},
3714 {"echo a{1..", "a{1..\n"},
3715 {
3716 "echo {00..2}; echo {01..10}; echo {1..10..-2}; echo {10..1..2}; echo {-03..3}",
3717 "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",
3718 },
3719 {"echo a{1..2}b{4..5}c", "a1b4c a1b5c a2b4c a2b5c\n"},
3720 {"echo a{c..f}", "ac ad ae af\n"},
3721 {"echo a{4..1..1}", "a4 a3 a2 a1\n"},
3722 {"b=c; echo ${b}a{4..1..1}", "ca4 ca3 ca2 ca1\n"},
3723 {"b=c; echo a{1,2}$b", "a1c a2c\n"},
3724 {"echo a{1,2}'bc'", "a1bc a2bc\n"},
3725 {`echo a\{1,2}b`, "a{1,2}b\n"},
3726 {`echo a{1,2\`, "a{1,2\\\n"},
3727 {`echo a{1,2\}b`, "a{1,2}b\n"},
3728 {`echo a{1\,2,3}b`, "a1,2b a3b\n"},
3729 {`echo a{1\}2,3}b`, "a1}2b a3b\n"},
3730 {`echo a{1\..2}b`, "a{1..2}b\n"},
3731 {`echo \{\{iriname\}\}`, "{{iriname}}\n"},
3732 {
3733 "echo {1..100000}",
3734 "brace expansion would exceed 16384 elements\n #IGNORE bash has no defensive limit below MaxInt",
3735 },
3736 {
•3737 "echo a{0..1999999999}b",
3738 "brace expansion would exceed 16384 elements\n #JUSTERR bash errors with a different message",
3739 },
3740
3741 // brace expansion in declarations
3742 {"declare {A,B}_VAR=1; echo $A_VAR $B_VAR", "1 1\n"},
3743 {"declare {x,y}=val; echo $x $y", "val val\n"},
3744 {"declare -x RUN_{VERY_,}EXPENSIVE_TESTS=yes; echo $RUN_EXPENSIVE_TESTS", "yes\n"},
3745 {"declare {A,B}_VAR; A_VAR=1; B_VAR=2; echo $A_VAR $B_VAR", "1 2\n"},
3746 {"declare {foo=x,bar=y}; echo $foo $bar", "x y\n"},
3747 {`declare foo{bar=baz`, "declare: invalid name \"foo{bar\"\nexit status 1 #JUSTERR"},
3748 {"{a,b}=value", "\"a=value\": executable file not found in $PATH\nexit status 127 #JUSTERR"},
3749
3750 // tilde expansion
3751 {
3752 "[[ '~/foo' == ~/foo ]] || [[ ~/foo == '~/foo' ]]",
3753 "exit status 1",
3754 },
3755 {
3756 "case '~/foo' in ~/foo) echo match ;; esac",
3757 "",
3758 },
3759 {
3760 "a=~/foo; [[ $a == '~/foo' ]]",
3761 "exit status 1",
3762 },
3763 {
3764 `a=$(echo "~/foo"); [[ $a == '~/foo' ]]`,
3765 "",
3766 },
3767 {
3768 `HOME=/foo; rel=/bar; echo ~/bar ~/'bar' ~/"bar" ~/$rel ~/"$rel"`,
3769 "/foo/bar /foo/bar /foo/bar /foo//bar /foo//bar\n",
3770 },
3771 {
3772 `HOME=/foo; rel=/bar; echo ~'/bar' ~"/bar" ~$rel ~"/$rel"`,
3773 "~/bar ~/bar ~/bar ~//bar\n",
3774 },
3775 {
3776 `HOME=/foo; echo ~ ~/ ~/'' ~'' ~""`,
3777 "/foo /foo/ /foo/ ~ ~\n",
3778 },
3779
3780 // /dev/null
3781 {"echo foo >/dev/null", ""},
3782 {"cat </dev/null", ""},
3783
3784 // time - real would be slow and flaky; see TestElapsedString
3785 {"{ time; } |& wc | tr -s ' '", " 4 6 42\n"},
3786 {"{ time echo -n; } |& wc | tr -s ' '", " 4 6 42\n"},
3787 {"{ time -p; } |& wc | tr -s ' '", " 3 6 29\n"},
3788 {"{ time -p echo -n; } |& wc | tr -s ' '", " 3 6 29\n"},
3789
3790 // exec
3791 {"exec", ""},
3792 {
3793 "exec builtin echo foo",
3794 "\"builtin\": executable file not found in $PATH\nexit status 127 #JUSTERR",
3795 },
3796 {
3797 "exec $GOSH_PROG 'echo foo'; echo bar",
3798 "foo\n",
3799 },
3800
3801 // read
3802 {
3803 "read </dev/null",
3804 "exit status 1",
3805 },
3806 {
3807 "read 1</dev/null",
3808 "exit status 1",
3809 },
3810 {
3811 "read -X",
3812 "read: invalid option \"-X\"\nexit status 2 #JUSTERR",
3813 },
3814 {
3815 "read -rX",
3816 "read: invalid option \"-X\"\nexit status 2 #JUSTERR",
3817 },
3818 {
3819 "read 0ab",
3820 "read: invalid identifier \"0ab\"\nexit status 2 #JUSTERR",
3821 },
3822 {
3823 "read <<< foo; echo $REPLY",
3824 "foo\n",
3825 },
3826 {
3827 "read <<<' a b c '; echo \"$REPLY\"",
3828 " a b c \n",
3829 },
3830 {
3831 "read <<< 'y\nn\n'; echo $REPLY",
3832 "y\n",
3833 },
3834 {
3835 "read a_0 <<< foo; echo $a_0",
3836 "foo\n",
3837 },
3838 {
3839 "read a b <<< 'foo bar baz '; echo \"$a\"; echo \"$b\"",
3840 "foo\nbar baz\n",
3841 },
3842 {
3843 "while read a; do echo $a; done <<< 'a\nb\nc'",
3844 "a\nb\nc\n",
3845 },
3846 {
3847 "while read a b; do echo -e \"$a\n$b\"; done <<< '1 2\n3'",
3848 "1\n2\n3\n\n",
3849 },
3850 {
3851 `read a <<< '\\'; echo "$a"`,
3852 "\\\n",
3853 },
3854 {
3855 `read a <<< '\a\b\c'; echo "$a"`,
3856 "abc\n",
3857 },
3858 {
3859 "read -r a b <<< '1\\\t2'; echo $a; echo $b;",
3860 "1\\\n2\n",
3861 },
3862 {
3863 "echo line\\\ncontinuation | while read a; do echo $a; done",
3864 "linecontinuation\n",
3865 },
3866 {
3867 "read x <<< $'foo\\\\\nbar'; echo \"$x\"",
3868 "foobar\n",
3869 },
3870 {
3871 "read x <<< $'a\\\\\nb\\\\\nc'; echo \"$x\"",
3872 "abc\n",
3873 },
3874 {
3875 "read -r x <<< $'foo\\\\\nbar'; echo \"$x\"",
3876 "foo\\\n",
3877 },
3878 {
3879 "while read a; do echo $a; GOSH_CMD=print_ok $GOSH_PROG; done <<< 'a\nb\nc'",
3880 "a\nexec ok\nb\nexec ok\nc\nexec ok\n",
3881 },
3882 {
3883 "while read a; do echo $a; GOSH_CMD=print_ok $GOSH_PROG; done <<EOF\na\nb\nc\nEOF",
3884 "a\nexec ok\nb\nexec ok\nc\nexec ok\n",
3885 },
3886 {
3887 "echo file1 >f; echo file2 >>f; while read a; do echo $a; done <f",
3888 "file1\nfile2\n",
3889 },
3890 // TODO: our final exit status here isn't right.
3891 // {
3892 // "while read a; do echo $a; GOSH_CMD=print_fail $GOSH_PROG; done <<< 'a\nb\nc'",
3893 // "a\nexec fail\nb\nexec fail\nc\nexec fail\nexit status 1",
3894 // },
3895 {
3896 `read -r a <<< '\\'; echo "$a"`,
3897 "\\\\\n",
3898 },
3899 {
3900 "read -r a <<< '\\a\\b\\c'; echo $a",
3901 "\\a\\b\\c\n",
3902 },
3903 {
3904 "IFS=: read a b c <<< '1:2:3'; echo $a; echo $b; echo $c",
3905 "1\n2\n3\n",
3906 },
3907 {
3908 "IFS=: read a b c <<< '1\\:2:3'; echo \"$a\"; echo $b; echo $c",
3909 "1:2\n3\n\n",
3910 },
3911 {
3912 `read x <<< ' a b '; echo "[$x]"`,
3913 "[a b]\n",
3914 },
3915 {
3916 `IFS=' :' read x <<< ' :a b: '; echo "[$x]"`,
3917 "[:a b:]\n",
3918 },
3919 {
3920 `IFS=: read x <<< ':a:b:'; echo "[$x]"`,
3921 "[:a:b:]\n",
3922 },
3923 {
3924 `read <<< ' a \b '; echo "[$REPLY]"; read -r <<< ' a\b '; echo "[$REPLY]"`,
3925 "[ a b ]\n[ a\\b ]\n",
3926 },
3927 {
3928 "read -p",
3929 "read: -p: option requires an argument\nexit status 2 #JUSTERR",
3930 },
3931 {
3932 "read -X -p",
3933 "read: invalid option \"-X\"\nexit status 2 #JUSTERR",
3934 },
3935 {
3936 "read -p 'Display me as a prompt. Continue? (y/n) ' choice <<< 'y'; echo $choice",
3937 "Display me as a prompt. Continue? (y/n) y\n #IGNORE bash requires a terminal",
3938 },
3939 {
3940 "read -r -p 'Prompt and raw flag together: ' a <<< '\\a\\b\\c'; echo $a",
3941 "Prompt and raw flag together: \\a\\b\\c\n #IGNORE bash requires a terminal",
3942 },
3943
3944 // read -s
3945 {
3946 "read -r -s x <<< hi; echo \"[$x]\"",
3947 "[hi]\n",
3948 },
3949 {
3950 "printf 'a b\\n' | { read -s -r a b; echo \"[$a][$b]\"; }",
3951 "[a][b]\n",
3952 },
3953
3954 // read -a
3955 {
3956 `echo "1 2 3" | { read -a arr; echo "${arr[0]} ${arr[1]} ${arr[2]}"; }`,
3957 "1 2 3\n",
3958 },
3959 {
3960 `echo "a b c" | { read -a arr; echo "${#arr[@]}"; }`,
3961 "3\n",
3962 },
3963 {
3964 `echo "" | { read -a arr; echo "${#arr[@]}"; }`,
3965 "0\n",
3966 },
3967 {
3968 `echo 'a\tb' | { read -ra arr; echo "${#arr[@]} ${arr[0]}"; }`,
3969 "1 a\\tb\n",
3970 },
3971 {
3972 `a=a; echo | (read a; echo -n "$a")`,
3973 "",
3974 },
3975 {
3976 `a=b; read a < /dev/null; echo -n "$a"`,
3977 "",
3978 },
3979 {
3980 "a=c; echo x | (read a; echo -n $a)",
3981 "x",
3982 },
3983 {
3984 "a=d; echo -n y | (read a; echo -n $a)",
3985 "y",
3986 },
3987
3988 // getopts
3989 {
3990 "getopts",
3991 "getopts: usage: getopts optstring name [arg ...]\nexit status 2",
3992 },
3993 {
3994 "getopts a a:b",
3995 "getopts: invalid identifier: \"a:b\"\nexit status 2 #JUSTERR",
3996 },
3997 {
3998 "getopts abc opt -a; echo $opt; $optarg",
3999 "a\n",
4000 },
4001 {
4002 "getopts abc opt -z",
4003 "getopts: illegal option -- \"z\"\n #IGNORE",
4004 },
4005 {
4006 "getopts a: opt -a",
4007 "getopts: option requires an argument -- \"a\"\n #IGNORE",
4008 },
4009 {
4010 "getopts :abc opt -z; echo $opt; echo $OPTARG",
4011 "?\nz\n",
4012 },
4013 {
4014 "getopts :a: opt -a; echo $opt; echo $OPTARG",
4015 ":\na\n",
4016 },
4017 {
4018 "getopts abc opt foo -a; echo $opt; echo $OPTIND",
4019 "?\n1\n",
4020 },
4021 {
4022 "getopts abc opt -a foo; echo $opt; echo $OPTIND",
4023 "a\n2\n",
4024 },
4025 {
4026 "OPTIND=3; getopts abc opt -a -b -c; echo $opt;",
4027 "c\n",
4028 },
4029 {
4030 "OPTIND=100; getopts abc opt -a -b -c; echo $opt;",
4031 "?\n",
4032 },
4033 {
4034 "OPTIND=foo; getopts abc opt -a -b -c; echo $opt;",
4035 "a\n",
4036 },
4037 {
4038 "while getopts ab:c opt -c -b arg -a foo; do echo $opt $OPTARG $OPTIND; done",
4039 "c 2\nb arg 4\na 5\n",
4040 },
4041 {
4042 "while getopts abc opt -ba -c foo; do echo $opt $OPTARG $OPTIND; done",
4043 "b 1\na 2\nc 3\n",
4044 },
4045 {
4046 "while getopts ab: opt -a -bval -a; do echo $opt $OPTARG $OPTIND; done",
4047 "a 2\nb val 3\na 4\n",
4048 },
4049 {
4050 "while getopts b: opt -bval foo; do echo $opt $OPTARG $OPTIND; done",
4051 "b val 2\n",
4052 },
4053 {
4054 "while getopts ab: opt -ab val; do echo $opt $OPTARG $OPTIND; done",
4055 "a 1\nb val 3\n",
4056 },
4057 {
4058 "a() { while getopts abc: opt; do echo $opt $OPTARG; done }; a -a -b -c arg",
4059 "a\nb\nc arg\n",
4060 },
4061 // mapfile
4062 {
4063 "mapfile <<EOF\na\nb\nc\nEOF\n" + `for x in "${MAPFILE[@]}"; do echo "$x"; done`,
4064 "a\n\nb\n\nc\n\n",
4065 },
4066 {
4067 "mapfile -t <<EOF\na\nb\nc\nEOF\n" + `for x in "${MAPFILE[@]}"; do echo "$x"; done`,
4068 "a\nb\nc\n",
4069 },
4070 {
4071 "mapfile -t -d b <<EOF\nabc\nEOF\n" + `for x in "${MAPFILE[@]}"; do echo "$x"; done`,
4072 "a\nc\n\n",
4073 },
4074 {
4075 "mapfile -t butter <<EOF\na\nb\nc\nEOF\n" + `for x in "${butter[@]}"; do echo "$x"; done`,
4076 "a\nb\nc\n",
4077 },
4078 }
4079
4080 var runTestsUnix = []runTest{
4081 {"[[ -n $PPID && $PPID -ge 0 ]]", ""}, // can be 0 if running as the init process
4082 {
4083 // no root user on windows
4084 "[[ ~root == '~root' ]]",
4085 "exit status 1",
4086 },
4087
4088 // windows does not support paths with '*'
4089 {
4090 "mkdir -p '*/a.z' 'b/a.z'; cd '*'; set -- *.z; echo $#",
4091 "1\n",
4092 },
4093 {
4094 "mkdir -p 'a-*/d'; test -d $PWD/a-*/*",
4095 "",
4096 },
4097
4098 // windows does not reliably track last-access time, so -N is unix-only
4099 {
4100 ">a; cat a; sleep 0.01; echo 'Hello' >> a; test -N a && echo yes",
4101 "yes\n",
4102 },
4103 {
4104 "test -N nonexistent",
4105 "exit status 1",
4106 },
4107 {
4108 ">a; sleep 0.01; cat a; test -N a; echo $?",
4109 "1\n",
4110 },
4111
4112 // no fifos on windows
4113 {
4114 "[ -p a ] && echo x; mkfifo a; [ -p a ] && echo y",
4115 "y\n",
4116 },
4117 {
4118 "[[ -p a ]] && echo x; mkfifo a; [[ -p a ]] && echo y",
4119 "y\n",
4120 },
4121
4122 {"sh() { :; }; sh -c 'echo foo'", ""},
4123 {"sh() { :; }; command sh -c 'echo foo'", "foo\n"},
4124
4125 // files without a shebang line are run as shell scripts; see issue #1065
4126 {
4127 "echo 'echo foo' >a; chmod +x a; ./a",
4128 "foo\n",
4129 },
4130 {
4131 "echo 'echo $#: $1' >a; chmod +x a; ./a one two",
4132 "2: one\n",
4133 },
4134 {
4135 "echo 'echo \"[$foo][$bar]\"' >a; chmod +x a; foo=1; export bar=2; ./a",
4136 "[][2]\n",
4137 },
4138 {
4139 "echo 'exit 5' >a; chmod +x a; ./a",
4140 "exit status 5",
4141 },
4142 {
4143 "printf '\\0\\n' >a; chmod +x a; ./a",
4144 "./a: cannot execute binary file\nexit status 126 #JUSTERR",
4145 },
4146 {
4147 "echo 'if' >a; chmod +x a; ./a",
4148 "./a:1:1: `if` must be followed by a statement list\nexit status 2 #JUSTERR",
4149 },
4150
4151 // chmod is practically useless on Windows
4152 {
4153 "[ -x a ] && echo x; >a; chmod 0755 a; [ -x a ] && echo y",
4154 "y\n",
4155 },
4156 {
4157 "[[ -x a ]] && echo x; >a; chmod 0755 a; [[ -x a ]] && echo y",
4158 "y\n",
4159 },
4160 {
4161 ">a; [ -k a ] && echo x; chmod +t a; [ -k a ] && echo y",
4162 "y\n",
4163 },
4164 {
4165 ">a; [ -u a ] && echo x; chmod u+s a; [ -u a ] && echo y",
4166 "y\n",
4167 },
4168 {
4169 ">a; [ -g a ] && echo x; chmod g+s a; [ -g a ] && echo y",
4170 "y\n",
4171 },
4172 {
4173 ">a; [[ -k a ]] && echo x; chmod +t a; [[ -k a ]] && echo y",
4174 "y\n",
4175 },
4176 {
4177 ">a; [[ -u a ]] && echo x; chmod u+s a; [[ -u a ]] && echo y",
4178 "y\n",
4179 },
4180 {
4181 ">a; [[ -g a ]] && echo x; chmod g+s a; [[ -g a ]] && echo y",
4182 "y\n",
4183 },
4184 {
4185 `mkdir a; chmod 0100 a; cd a`,
4186 "",
4187 },
4188 // Note that these will succeed if we're root.
4189 {
4190 `mkdir a; chmod 0000 a; cd a`,
4191 "cd: permission denied: \"a\"\nexit status 1 #JUSTERR",
4192 },
4193 {
4194 `mkdir a; chmod 0222 a; cd a`,
4195 "cd: permission denied: \"a\"\nexit status 1 #JUSTERR",
4196 },
4197 {
4198 `mkdir a; chmod 0444 a; cd a`,
4199 "cd: permission denied: \"a\"\nexit status 1 #JUSTERR",
4200 },
4201 {
4202 `mkdir a; chmod 0010 a; cd a`,
4203 "cd: permission denied: \"a\"\nexit status 1 #JUSTERR",
4204 },
4205 {
4206 `mkdir a; chmod 0001 a; cd a`,
4207 "cd: permission denied: \"a\"\nexit status 1 #JUSTERR",
4208 },
4209 {
4210 `unset UID`,
4211 "UID: readonly variable\n #IGNORE",
4212 },
4213 {
4214 `test -n "$EUID" && echo OK`,
4215 "OK\n",
4216 },
4217 {
4218 `set EUID=newvalue; test EUID != newvalue && echo OK || echo EUID=$EUID`,
4219 "OK\n",
4220 },
4221 {
4222 `unset EUID`,
4223 "EUID: readonly variable\n #IGNORE",
4224 },
4225 // GID is not set in bash
4226 {
4227 `unset GID`,
4228 "GID: readonly variable\n #IGNORE",
4229 },
4230 {
4231 `[[ -z $GID ]] && echo "GID not set"`,
4232 "exit status 1 #JUSTERR #IGNORE",
4233 },
4234
4235 // Unix-y PATH
4236 {
4237 "PATH=; bash -c 'echo foo'",
4238 "\"bash\": executable file not found in $PATH\nexit status 127 #JUSTERR",
4239 },
4240 {
4241 "cd /; sure/is/missing",
4242 "stat /sure/is/missing: no such file or directory\nexit status 127 #JUSTERR",
4243 },
4244 {
4245 "echo '#!/bin/sh\necho b' >a; chmod 0755 a; PATH=; a",
4246 "b\n",
4247 },
4248 {
4249 "mkdir c; cd c; echo '#!/bin/sh\necho b' >a; chmod 0755 a; PATH=; a",
4250 "b\n",
4251 },
4252 {
4253 "mkdir c; echo '#!/bin/sh\necho b' >c/a; chmod 0755 c/a; c/a",
4254 "b\n",
4255 },
4256 {
4257 "GOSH_CMD=lookpath $GOSH_PROG",
4258 "sh found\n",
4259 },
4260
4261 // error strings which are too different on Windows
4262 {
4263 "echo foo >/shouldnotexist/file",
4264 "open /shouldnotexist/file: no such file or directory\nexit status 1 #JUSTERR",
4265 },
4266 {
4267 "set -e; echo foo >/shouldnotexist/file; echo foo",
4268 "open /shouldnotexist/file: no such file or directory\nexit status 1 #JUSTERR",
4269 },
4270
4271 // process substitution; named pipes (fifos) are a TODO for windows
4272 {
4273 "sed 's/o/e/g' <(echo foo bar)",
4274 "fee bar\n",
4275 },
4276 {
4277 "cat <(echo foo) <(echo bar) <(echo baz)",
4278 "foo\nbar\nbaz\n",
4279 },
4280 {
4281 "cat <(cat <(echo nested))",
4282 "nested\n",
4283 },
4284 {
4285 // The tests here use "wait" because otherwise the parent may finish before
4286 // the subprocess has had time to process the input and print the result.
4287 "echo foo bar > >(sed 's/o/e/g'); wait",
4288 "fee bar\n",
4289 },
4290 {
4291 "echo foo bar | tee >(sed 's/o/e/g') >/dev/null; wait",
4292 "fee bar\n",
4293 },
4294 {
4295 "echo nested > >(cat > >(cat); wait); wait",
4296 "nested\n",
4297 },
4298 {
4299 "cat <(exit 0); wait $!; echo $?",
4300 "0\n",
4301 },
4302 {
4303 "cat <(exit 5); wait $!; echo $?",
4304 "5\n",
4305 },
4306 {
4307 // The reader here does not consume the named pipe.
4308 "test -e <(echo foo)",
4309 "",
4310 },
4311 // echo trace
4312 {
4313 `set -x; animals=("dog", "cat", "otter"); echo "hello ${animals[*]}"`,
4314 `+ animals=("dog", "cat", "otter")
4315 + echo 'hello dog, cat, otter'
4316 hello dog, cat, otter
4317 `,
4318 },
4319 {
4320 `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"`,
4321 `+ s='always print a decimal point for %e, %E, %f, %F, %g and %G; do not remove trailing zeros for %g and %G'
4322 + echo 'always print a decimal point for %e, %E, %f, %F, %g and %G; do not remove trailing zeros for %g and %G'
4323 always print a decimal point for %e, %E, %f, %F, %g and %G; do not remove trailing zeros for %g and %G
4324 `,
4325 },
4326 {
4327 `set -x
4328 x=without; echo "$x"
4329 x="double quote"; echo "$x"
4330 x='single quote'; echo "$x"`,
4331 `+ x=without
4332 + echo without
4333 without
4334 + x='double quote'
4335 + echo 'double quote'
4336 double quote
4337 + x='single quote'
4338 + echo 'single quote'
4339 single quote
4340 `,
4341 },
4342 // for trace
4343 {
4344 `set -x
4345 exec >/dev/null
4346 echo "trace should go to stderr"`,
4347 `+ exec
4348 + echo 'trace should go to stderr'
4349 `,
4350 },
4351 {
4352 `set -x
4353 animals=(dog, cat, otter)
4354 for i in ${animals[@]}
4355 do
4356 echo "hello ${i}"
4357 done
4358 `,
4359 `+ animals=(dog, cat, otter)
4360 + for i in ${animals[@]}
4361 + echo 'hello dog,'
4362 hello dog,
4363 + for i in ${animals[@]}
4364 + echo 'hello cat,'
4365 hello cat,
4366 + for i in ${animals[@]}
4367 + echo 'hello otter'
4368 hello otter
4369 `,
4370 },
4371 {
4372 `set -x
4373 loop() {
4374 for i do
4375 echo "something with $i"
4376 done
4377 }
4378 loop 1 2 3`,
4379 `+ loop 1 2 3
4380 + for i in "$@"
4381 + echo 'something with 1'
4382 something with 1
4383 + for i in "$@"
4384 + echo 'something with 2'
4385 something with 2
4386 + for i in "$@"
4387 + echo 'something with 3'
4388 something with 3
4389 `,
4390 },
4391 {
4392 `set -x; animals=(dog, cat, otter); for i in ${animals[@]}; do echo "hello ${i}"; done`,
4393 `+ animals=(dog, cat, otter)
4394 + for i in ${animals[@]}
4395 + echo 'hello dog,'
4396 hello dog,
4397 + for i in ${animals[@]}
4398 + echo 'hello cat,'
4399 hello cat,
4400 + for i in ${animals[@]}
4401 + echo 'hello otter'
4402 hello otter
4403 `,
4404 },
4405 {
4406 "set -x; set -e; echo hi",
4407 "+ set -e\n+ echo hi\nhi\n",
4408 },
4409 {
4410 "set -x; set +x; echo hi",
4411 "+ set +x\nhi\n",
4412 },
4413 {
4414 // TODO: bash prints `a[1]=z`, including the subscript.
4415 `set -x; a=(x y); a[1]=z`,
4416 "+ a=(x y)\n+ a=z\n #IGNORE",
4417 },
4418 {
4419 // TODO: bash prints `a+=bar`, that is, the value being appended
4420 // rather than the resulting value.
4421 `set -x; a=foo; a+=bar`,
4422 "+ a=foo\n+ a=foobar\n #IGNORE",
4423 },
4424 {
4425 `set -x; a=(x); a+=(y)`,
4426 "+ a=(x)\n+ a+=(y)\n",
4427 },
4428 {
4429 `set -x; a=x"y"$z b=(foo bar $none '')`,
4430 "+ a=xy\n+ b=(foo bar $none '')\n",
4431 },
4432 {
4433 `set -x; for i in a b; do echo $i; done`,
4434 `+ for i in a b
4435 + echo a
4436 a
4437 + for i in a b
4438 + echo b
4439 b
4440 `,
4441 },
4442 {
4443 `set -x; for i in $none_a $none_b; do echo $i; done`,
4444 ``,
4445 },
4446 // case trace
4447 {
4448 `set -x; pet=dog; case $pet in 'dog') echo "barks";; *) echo "unknown";; esac`,
4449 `+ pet=dog
4450 + case $pet in
4451 + echo barks
4452 barks
4453 `,
4454 },
4455 {
4456 `set -x
4457 pet="dog"
4458 case $pet in
4459 dog)
4460 echo "barks"
4461 ;;
4462 *)
4463 echo "unknown"
4464 ;;
4465 esac`,
4466 `+ pet=dog
4467 + case $pet in
4468 + echo barks
4469 barks
4470 `,
4471 },
4472 // arithmetic
4473 {
4474 `set -x
4475 a=$(( 4 + 5 )); echo $a
4476 a=$((3+5)); echo $a`,
4477 `+ a=9
4478 + echo 9
4479 9
4480 + a=8
4481 + echo 8
4482 8
4483 `,
4484 },
4485 {
4486 `set -x;
4487 let a=5+4; echo $a
4488 let "a = 5 + 4"; echo $a
4489 let a++; echo $a`,
4490 `+ let a=5+4
4491 + echo 9
4492 9
4493 + let 'a = 5 + 4'
4494 + echo 9
4495 9
4496 + let a++
4497 + echo 10
4498 10
4499 `,
4500 },
4501 {
4502 `set -x; let a=1 b=2`,
4503 "+ let a=1 b=2\n",
4504 },
4505 {
4506 // Note that bash cannot parse `let (a=3)` at all.
4507 `set -x; let (a=3)`,
4508 "+ let (a = 3)\n #IGNORE",
4509 },
4510 // functions
4511 {
4512 `set -x; function with_function () { echo 'hello, world'; }; with_function`,
4513 `+ with_function
4514 + echo 'hello, world'
4515 hello, world
4516 `,
4517 },
4518 {
4519 `set -x; without_function () { echo 'hello, world'; }; without_function`,
4520 `+ without_function
4521 + echo 'hello, world'
4522 hello, world
4523 `,
4524 },
4525 {
4526 // globbing wildcard as function name
4527 `@() { echo "$@"; }; @ lala; function +() { echo "$@"; }; + foo`,
4528 "lala\nfoo\n",
4529 },
4530 {
4531 ` @() { echo "$@"; }; @ lala;`,
4532 "lala\n",
4533 },
4534 {
4535 // globbing wildcard as function name but with space after the name
4536 `+ () { echo "$@"; }; + foo; @ () { echo "$@"; }; @ lala; ? () { echo "$@"; }; ? bar`,
4537 "foo\nlala\nbar\n",
4538 },
4539 // mapfile, no process substitution yet on Windows
4540 {
4541 `mapfile -t -d "" < <(printf "a\0b\n"); for x in "${MAPFILE[@]}"; do echo "$x"; done`,
4542 "a\nb\n\n",
4543 },
4544 // Windows does not support having a `\n` in a filename
4545 {
4546 `> $'bar\nbaz'; echo bar*baz`,
4547 "bar\nbaz\n",
4548 },
4549 }
4550
4551 var runTestsWindows = []runTest{
4552 {"[[ -n $PPID || $PPID -gt 0 ]]", ""}, // os.Getppid can be 0 on windows
4553 {"cmd() { :; }; cmd /c 'echo foo'", ""},
4554 {"cmd() { :; }; command cmd /c 'echo foo'", "foo\r\n"},
4555 {
4556 "GOSH_CMD=lookpath $GOSH_PROG",
4557 "cmd found\n",
4558 },
4559 {
4560 "localCase=camel; LocalCase=pascal; echo $localcase",
4561 "pascal\n",
4562 },
4563 {
4564 // Matching the env var name set as a global
4565 // in a case sensitive way.
4566 "$ENV_PROG | grep -i '^mixedCase_interp'",
4567 "mixedCase_INTERP_GLOBAL=value\n",
4568 },
4569 {
4570 // Overwriting the env var set as a global
4571 // in a case insensitive way.
4572 "MIXEDCASE_interp_global=replaced; echo $MIXEDCASE_interp_GLOBAL",
4573 "replaced\n",
4574 },
4575 {
4576 "MIXEDCASE_interp_global=replaced; $ENV_PROG | grep -i '^mixedcase_interp'",
4577 "MIXEDCASE_interp_global=replaced\n",
4578 },
4579 }
4580
4581 // These tests are specific to 64-bit architectures, and that's fine. We don't
4582 // need to add explicit versions for 32-bit.
4583 var runTests64bit = []runTest{
4584 {"printf %i,%u -3 -3", "-3,18446744073709551613"},
4585 {"printf %o -3", "1777777777777777777775"},
4586 {"printf %x -3", "fffffffffffffffd"},
4587 }
4588
4589 func init() {
4590 switch {
4591 case runtime.GOOS == "windows":
4592 runTests = append(runTests, runTestsWindows...)
4593 case runtime.GOOS == "js":
4594 // Neither Unix-y nor Windows: js/wasm has no subprocesses,
4595 // and its file modes and syscall errors differ from Unix.
4596 default: // Unix-y
4597 runTests = append(runTests, runTestsUnix...)
4598 }
4599 if bits.UintSize == 64 {
4600 runTests = append(runTests, runTests64bit...)
4601 }
4602 }
4603
4604 // ln -s: wine doesn't implement symlinks; see https://bugs.winehq.org/show_bug.cgi?id=44948
4605 // process substitutions are not supported on Windows
4606 var skipOnWindows = regexp.MustCompile(`ln -s|<\(`)
4607
4608 // process substitutions seemflaky on mac; see https://github.com/mvdan/sh/issues/576
4609 var skipOnMac = regexp.MustCompile(`>\(|<\(`)
4610
4611 // canExec reports whether the platform can run external programs.
4612 // js/wasm has no subprocesses at all.
4613 const canExec = runtime.GOOS != "js"
4614
4615 // Without subprocesses we can't run the test binary as a helper program,
4616 // nor any external program, nor create the named pipes used by process
4617 // substitutions.
4618 var skipWithoutExec = regexp.MustCompile(`GOSH_PROG|ENV_PROG|PATH_PROG|>\(|<\(`)
4619
4620 func skipIfUnsupported(tb testing.TB, src string) {
4621 switch {
4622 case runtime.GOOS == "windows" && skipOnWindows.MatchString(src):
4623 tb.Skipf("skipping non-portable test on windows")
4624 case runtime.GOOS == "darwin" && skipOnMac.MatchString(src):
4625 tb.Skipf("skipping non-portable test on mac")
4626 case !canExec && skipWithoutExec.MatchString(src):
4627 tb.Skipf("skipping test needing subprocesses on %s", runtime.GOOS)
4628 }
4629 }
4630
4631 func TestRunnerRun(t *testing.T) {
4632 t.Parallel()
4633
4634 p := syntax.NewParser()
4635 for _, c := range runTests {
4636 t.Run("", func(t *testing.T) {
4637 skipIfUnsupported(t, c.in)
4638 t.Logf("input: %q", c.in)
4639
4640 // Parse first, as we reuse a single parser.
4641 file := parse(t, p, c.in)
4642
4643 t.Parallel()
4644
4645 tdir := t.TempDir()
4646 var cb concBuffer
4647 r, err := interp.New(interp.Dir(tdir), interp.StdIO(nil, &cb, &cb),
4648 // TODO: why does this make some tests hang?
4649 // interp.Env(expand.ListEnviron(append(os.Environ(),
4650 // "foo_NULL_BAR=foo\x00bar")...)),
4651 interp.ExecHandlers(testExecHandler),
4652 )
4653 if err != nil {
4654 t.Fatal(err)
4655 }
4656 ctx, cancel := context.WithTimeout(t.Context(), runnerRunTimeout)
4657 defer cancel()
4658 if err := r.Run(ctx, file); err != nil {
4659 cb.WriteString(err.Error())
4660 }
4661
4662 // Some builtins like "pushd" can show absolute paths as part of error messages.
4663 // Allow a very simple search-and-replace for the equivalent to "$PWD/a".
4664 want := strings.ReplaceAll(c.want, "ABS_PATH_A", fmt.Sprintf("%q", filepath.Join(tdir, "a")))
4665
4666 if i := strings.Index(want, " #"); i >= 0 {
4667 want = want[:i]
4668 }
4669 if got := cb.String(); got != want {
4670 if len(got) > 200 {
4671 got = "…" + got[len(got)-200:]
4672 }
4673 t.Fatalf("wrong output in %q:\nwant: %q\ngot: %q",
4674 c.in, want, got)
4675 }
4676 })
4677 }
4678 }
4679
4680 func TestRunnerUnsupported(t *testing.T) {
4681 t.Parallel()
4682
4683 // Features from language variants that the interpreter does not
4684 // support, such as zsh, should error rather than panic.
4685 tests := []struct {
4686 lang syntax.LangVariant
4687 in string
4688 want string
4689 }{
4690 {syntax.LangZsh, "echo x${}y", "unsupported\n"},
4691 {syntax.LangZsh, `echo "${}"`, "unsupported\n"},
4692 {syntax.LangZsh, "echo ${:-foo}", "unsupported\n"},
4693 {syntax.LangZsh, "echo ${+a}", "unsupported\n"},
4694 {syntax.LangZsh, "a=abc; echo ${a[(r)b]}", "unsupported\n"},
4695 {syntax.LangZsh, "() { echo anon; }", "unsupported\nexit status 1"},
4696 {syntax.LangZsh, "function { echo anon; }", "unsupported\nexit status 1"},
4697 {syntax.LangZsh, "function f g { echo multi; }", "unsupported\nexit status 1"},
4698 {syntax.LangZsh, "cat =(echo hi)", "unsupported\n"},
4699 {syntax.LangMirBSDKorn, "echo ${%a}", "unsupported\n"},
4700 }
4701 for _, tc := range tests {
4702 t.Run("", func(t *testing.T) {
4703 t.Parallel()
4704 t.Logf("input: %q", tc.in)
4705 p := syntax.NewParser(syntax.Variant(tc.lang))
4706 file := parse(t, p, tc.in)
4707 var cb concBuffer
4708 r, err := interp.New(interp.StdIO(nil, &cb, &cb))
4709 if err != nil {
4710 t.Fatal(err)
4711 }
4712 ctx, cancel := context.WithTimeout(t.Context(), runnerRunTimeout)
4713 defer cancel()
4714 if err := r.Run(ctx, file); err != nil {
4715 cb.WriteString(err.Error())
4716 }
4717 if got := cb.String(); got != tc.want {
4718 t.Fatalf("wrong output in %q:\nwant: %q\ngot: %q",
4719 tc.in, tc.want, got)
4720 }
4721 })
4722 }
4723 }
4724
4725 func readLines(hc interp.HandlerContext) ([][]byte, error) {
4726 bs, err := io.ReadAll(hc.Stdin)
4727 if err != nil {
4728 return nil, err
4729 }
4730 if runtime.GOOS == "windows" {
4731 bs = bytes.ReplaceAll(bs, []byte("\r\n"), []byte("\n"))
4732 }
4733 bs = bytes.TrimSuffix(bs, []byte("\n"))
4734 return bytes.Split(bs, []byte("\n")), nil
4735 }
4736
4737 func absPath(dir, path string) string {
4738 if path == "" {
4739 return ""
4740 }
4741 if !filepath.IsAbs(path) {
4742 path = filepath.Join(dir, path)
4743 }
4744 // Keep in sync with interp's own absPath, which explains the cleaning.
4745 return filepath.Clean(path)
4746 }
4747
4748 var testBuiltinsMap = map[string]func(interp.HandlerContext, []string) error{
4749 "cat": func(hc interp.HandlerContext, args []string) error {
4750 if len(args) == 0 {
4751 if hc.Stdin == nil || hc.Stdout == nil {
4752 return nil
4753 }
4754 _, err := io.Copy(hc.Stdout, hc.Stdin)
4755 return err
4756 }
4757 for _, arg := range args {
4758 path := absPath(hc.Dir, arg)
4759 f, err := os.Open(path)
4760 if err != nil {
4761 return err
4762 }
4763 _, err = io.Copy(hc.Stdout, f)
4764 f.Close()
4765 if err != nil {
4766 return err
4767 }
4768 }
4769 return nil
4770 },
4771 "wc": func(hc interp.HandlerContext, args []string) error {
4772 bs, err := io.ReadAll(hc.Stdin)
4773 if err != nil {
4774 return err
4775 }
4776 if len(args) == 0 {
4777 fmt.Fprintf(hc.Stdout, "%7d", bytes.Count(bs, []byte("\n")))
4778 fmt.Fprintf(hc.Stdout, "%8d", len(bytes.Fields(bs)))
4779 fmt.Fprintf(hc.Stdout, "%8d\n", len(bs))
4780 } else if args[0] == "-c" {
4781 fmt.Fprintln(hc.Stdout, len(bs))
4782 } else if args[0] == "-l" {
4783 fmt.Fprintln(hc.Stdout, bytes.Count(bs, []byte("\n")))
4784 }
4785 return nil
4786 },
4787 "tr": func(hc interp.HandlerContext, args []string) error {
4788 if len(args) != 2 || len(args[1]) != 1 {
4789 return fmt.Errorf("usage: tr [-s -d] [character]")
4790 }
4791 squeeze := args[0] == "-s"
4792 char := args[1][0]
4793 bs, err := io.ReadAll(hc.Stdin)
4794 if err != nil {
4795 return err
4796 }
4797 for {
4798 i := bytes.IndexByte(bs, char)
4799 if i < 0 {
4800 hc.Stdout.Write(bs) // remaining
4801 break
4802 }
4803 hc.Stdout.Write(bs[:i]) // up to char
4804 bs = bs[i+1:]
4805
4806 bs = bytes.TrimLeft(bs, string(char)) // remove repeats
4807 if squeeze {
4808 hc.Stdout.Write([]byte{char})
4809 }
4810 }
4811 return nil
4812 },
4813 "sort": func(hc interp.HandlerContext, args []string) error {
4814 lines, err := readLines(hc)
4815 if err != nil {
4816 return err
4817 }
4818 slices.SortFunc(lines, bytes.Compare)
4819 for _, line := range lines {
4820 fmt.Fprintf(hc.Stdout, "%s\n", line)
4821 }
4822 return nil
4823 },
4824 "grep": func(hc interp.HandlerContext, args []string) error {
4825 var rx *regexp.Regexp
4826 quiet := false
4827 caseInsensitive := false
4828 for _, arg := range args {
4829 if arg == "-q" {
4830 quiet = true
4831 } else if arg == "-i" {
4832 caseInsensitive = true
4833 } else if arg == "-E" {
4834 } else if rx == nil {
4835 if caseInsensitive {
4836 arg = "(?i)" + arg
4837 }
4838 rx = regexp.MustCompile(arg)
4839 } else {
4840 return fmt.Errorf("unexpected arg: %q", arg)
4841 }
4842 }
4843 lines, err := readLines(hc)
4844 if err != nil {
4845 return err
4846 }
4847 anyMatch := false
4848 for _, line := range lines {
4849 if rx.Match(line) {
4850 if quiet {
4851 return nil
4852 }
4853 anyMatch = true
4854 fmt.Fprintf(hc.Stdout, "%s\n", line)
4855 }
4856 }
4857 if !anyMatch {
4858 return interp.ExitStatus(1)
4859 }
4860 return nil
4861 },
4862 "sed": func(hc interp.HandlerContext, args []string) error {
4863 f := hc.Stdin
4864 switch len(args) {
4865 case 1:
4866 case 2:
4867 var err error
4868 f, err = os.Open(absPath(hc.Dir, args[1]))
4869 if err != nil {
4870 return err
4871 }
4872 default:
4873 return fmt.Errorf("usage: sed pattern [file]")
4874 }
4875 expr := args[0]
4876 if expr == "" || expr[0] != 's' {
4877 return fmt.Errorf("unimplemented")
4878 }
4879 sep := expr[1]
4880 expr = expr[2:]
4881 from := expr[:strings.IndexByte(expr, sep)]
4882 expr = expr[len(from)+1:]
4883 to := expr[:strings.IndexByte(expr, sep)]
4884 bs, err := io.ReadAll(f)
4885 if err != nil {
4886 return err
4887 }
4888 rx := regexp.MustCompile(from)
4889 bs = rx.ReplaceAllLiteral(bs, []byte(to))
4890 _, err = hc.Stdout.Write(bs)
4891 return err
4892 },
4893 "mkdir": func(hc interp.HandlerContext, args []string) error {
4894 for _, arg := range args {
4895 if arg == "-p" {
4896 continue
4897 }
4898 path := absPath(hc.Dir, arg)
4899 if err := os.MkdirAll(path, 0o777); err != nil {
4900 return err
4901 }
4902 }
4903 return nil
4904 },
4905 "rm": func(hc interp.HandlerContext, args []string) error {
4906 for _, arg := range args {
4907 if arg == "-r" {
4908 continue
4909 }
4910 path := absPath(hc.Dir, arg)
4911 if err := os.RemoveAll(path); err != nil {
4912 return err
4913 }
4914 }
4915 return nil
4916 },
4917 "ln": func(hc interp.HandlerContext, args []string) error {
4918 symbolic := args[0] == "-s"
4919 if symbolic {
4920 args = args[1:]
4921 }
4922 oldname := absPath(hc.Dir, args[0])
4923 newname := absPath(hc.Dir, args[1])
4924 if symbolic {
4925 return os.Symlink(oldname, newname)
4926 }
4927 return os.Link(oldname, newname)
4928 },
4929 "touch": func(hc interp.HandlerContext, args []string) error {
4930 filenames := args // create all arguments as filenames
4931
4932 newTime := time.Now()
4933 if args[0] == "-t" {
4934 if len(args) < 3 {
4935 return fmt.Errorf("usage: touch [-t [[CC]YY]MMDDhhmm[.SS]] file")
4936 }
4937 filenames = args[2:] // treat the rest of the args as filenames
4938
4939 arg := args[1]
4940 if len(arg) > 15 {
4941 return fmt.Errorf("usage: touch [-t [[CC]YY]MMDDhhmm[.SS]] file")
4942 }
4943 s, err := time.Parse("200601021504.05", arg)
4944 if err != nil {
4945 return err
4946 }
4947 newTime = s
4948 }
4949
4950 for _, arg := range filenames {
4951 if strings.HasPrefix(arg, "-") {
4952 return fmt.Errorf("usage: touch [-t [[CC]YY]MMDDhhmm[.SS]] file")
4953 }
4954 path := absPath(hc.Dir, arg)
4955 // create the file if it does not exist
4956 f, err := os.OpenFile(path, os.O_CREATE, 0o666)
4957 if err != nil {
4958 return err
4959 }
4960 f.Close()
4961 // change the modification and access time
4962 if err := os.Chtimes(path, newTime, newTime); err != nil {
4963 return err
4964 }
4965 }
4966 return nil
4967 },
4968 "sleep": func(hc interp.HandlerContext, args []string) error {
4969 for _, arg := range args {
4970 // assume and default unit to be in seconds
4971 d, err := time.ParseDuration(fmt.Sprintf("%ss", arg))
4972 if err != nil {
4973 return err
4974 }
4975 time.Sleep(d)
4976 }
4977 return nil
4978 },
4979 }
4980
4981 func testExecHandler(next interp.ExecHandlerFunc) interp.ExecHandlerFunc {
4982 return func(ctx context.Context, args []string) error {
4983 if fn := testBuiltinsMap[args[0]]; fn != nil {
4984 return fn(interp.HandlerCtx(ctx), args[1:])
4985 }
4986 return next(ctx, args)
4987 }
4988 }
4989
4990 // Same as the syntax package.
4991 var requireShells = os.Getenv("REQUIRE_SHELLS") == "1"
4992
4993 func TestRunnerRunConfirm(t *testing.T) {
4994 if testing.Short() {
4995 t.Skip("calling bash is slow")
4996 }
4997 if !hasBash53 {
4998 if requireShells {
4999 t.Fatal("bash 5.3 required to run")
5000 } else {
5001 t.Skip("bash 5.3 required to run")
5002 }
5003 }
5004 t.Parallel()
5005
5006 if runtime.GOOS == "windows" {
5007 // For example, it seems to treat environment variables as
5008 // case-sensitive, which isn't how Windows works.
5009 t.Skip("bash on Windows emulates Unix-y behavior")
5010 }
5011 for _, c := range runTests {
5012 t.Run("", func(t *testing.T) {
5013 if strings.Contains(c.want, " #IGNORE") {
5014 return
5015 }
5016 skipIfUnsupported(t, c.in)
5017 t.Parallel()
5018 tdir := t.TempDir()
5019 ctx, cancel := context.WithTimeout(t.Context(), runnerRunTimeout)
5020 defer cancel()
5021 cmd := exec.CommandContext(ctx, "bash")
5022 cmd.Dir = tdir
5023 cmd.Stdin = strings.NewReader(c.in)
5024 out, err := cmd.CombinedOutput()
5025 if strings.Contains(c.want, " #JUSTERR") {
5026 // bash sometimes exits with status code 0 and
5027 // stderr "bash: ..." for an error
5028 fauxErr := bytes.HasPrefix(out, []byte("bash:"))
5029 if err == nil && !fauxErr {
5030 t.Fatalf("wanted bash to error in %q", c.in)
5031 }
5032 return
5033 }
5034 got := string(out)
5035 if err != nil {
5036 got += err.Error()
5037 }
5038 if got != c.want {
5039 t.Fatalf("wrong bash output in %q:\nwant: %q\ngot: %q",
5040 c.in, c.want, got)
5041 }
5042 })
5043 }
5044 }
5045
5046 func TestRunnerOpts(t *testing.T) {
5047 t.Parallel()
5048
5049 withPath := func(strs ...string) func(*interp.Runner) error {
5050 prefix := []string{
5051 "PATH=" + os.Getenv("PATH"),
5052 "ENV_PROG=" + os.Getenv("ENV_PROG"),
5053 }
5054 return interp.Env(expand.ListEnviron(append(prefix, strs...)...))
5055 }
5056 opts := func(list ...interp.RunnerOption) []interp.RunnerOption {
5057 return list
5058 }
5059 cases := []struct {
5060 opts []interp.RunnerOption
5061 in, want string
5062 }{
5063 {
5064 nil,
5065 "$ENV_PROG | grep -i '^interp_global='",
5066 "INTERP_GLOBAL=value\n",
5067 },
5068 {
5069 opts(withPath()),
5070 "$ENV_PROG | grep -i '^interp_global='",
5071 "exit status 1",
5072 },
5073 {
5074 opts(withPath("INTERP_GLOBAL=bar")),
5075 "$ENV_PROG | grep -i '^interp_global='",
5076 "INTERP_GLOBAL=bar\n",
5077 },
5078 {
5079 opts(withPath("a=b")),
5080 "echo $a",
5081 "b\n",
5082 },
5083 {
5084 opts(withPath("A=b")),
5085 "$ENV_PROG | grep '^A='; echo $A",
5086 "A=b\nb\n",
5087 },
5088 {
5089 opts(withPath("A=b", "A=c")),
5090 "$ENV_PROG | grep '^A='; echo $A",
5091 "A=c\nc\n",
5092 },
5093 {
5094 opts(withPath("HOME=")),
5095 "echo $HOME",
5096 "\n",
5097 },
5098 {
5099 opts(withPath("PWD=foo")),
5100 "[[ $PWD == foo ]]",
5101 "exit status 1",
5102 },
5103 {
5104 opts(interp.Params("foo")),
5105 "echo $@",
5106 "foo\n",
5107 },
5108 {
5109 opts(interp.Params("-u", "--", "foo")),
5110 "echo $@; echo $unset",
5111 "foo\nunset: unbound variable\nexit status 1",
5112 },
5113 {
5114 opts(interp.Params("-u", "--", "foo")),
5115 "echo $@; echo ${unset:-default}",
5116 "foo\ndefault\n",
5117 },
5118 {
5119 opts(interp.Params("foo")),
5120 "set >/dev/null; echo $@",
5121 "foo\n",
5122 },
5123 {
5124 opts(interp.Params("foo")),
5125 "set -e; echo $@",
5126 "foo\n",
5127 },
5128 {
5129 opts(interp.Params("foo")),
5130 "set --; echo $@",
5131 "\n",
5132 },
5133 {
5134 opts(interp.Params("foo")),
5135 "set bar; echo $@",
5136 "bar\n",
5137 },
5138 {
5139 opts(interp.BashOpts()),
5140 "echo foo",
5141 "foo\n",
5142 },
5143 {
5144 opts(interp.BashOpts("-s", "expand_aliases")),
5145 "alias f='echo x'\nf",
5146 "x\n",
5147 },
5148 {
5149 opts(interp.BashOpts("-s", "extglob", "nullglob")),
5150 "[[ abc == @(abc|def) ]] && echo yes\necho no-match-*",
5151 "yes\n\n",
5152 },
5153 {
5154 opts(interp.BashOpts("-s", "globstar"), interp.BashOpts("-u", "globstar")),
5155 "shopt globstar | grep -q 'off$'",
5156 "",
5157 },
5158 {
5159 opts(interp.BashOpts("-o", "-s", "pipefail")),
5160 "false | true; echo $?",
5161 "1\n",
5162 },
5163 {
5164 opts(interp.BashOpts("-o", "-s", "noglob")),
5165 "echo *",
5166 "*\n",
5167 },
5168 {
5169 opts(interp.Env(expand.FuncEnviron(func(name string) string {
5170 if name == "foo" {
5171 return "bar"
5172 }
5173 return ""
5174 }))),
5175 "(echo $foo); echo x | echo $foo",
5176 "bar\nbar\n",
5177 },
5178 }
5179 p := syntax.NewParser()
5180 for _, c := range cases {
5181 t.Run("", func(t *testing.T) {
5182 skipIfUnsupported(t, c.in)
5183 file := parse(t, p, c.in)
5184 var cb concBuffer
5185 r, err := interp.New(append(c.opts,
5186 interp.StdIO(nil, &cb, &cb),
5187 interp.ExecHandlers(testExecHandler),
5188 )...)
5189 if err != nil {
5190 t.Fatal(err)
5191 }
5192 ctx, cancel := context.WithTimeout(t.Context(), runnerRunTimeout)
5193 defer cancel()
5194 if err := r.Run(ctx, file); err != nil {
5195 cb.WriteString(err.Error())
5196 }
5197 if got := cb.String(); got != c.want {
5198 t.Fatalf("wrong output in %q:\nwant: %q\ngot: %q",
5199 c.in, c.want, got)
5200 }
5201 })
5202 }
5203 }
5204
5205 func TestRunnerBashOpts(t *testing.T) {
5206 t.Parallel()
5207
5208 // Applying the option to an existing runner takes effect right away,
5209 // including for the options which affect expansion.
5210 file := parse(t, nil, "echo no-match-*")
5211 var b bytes.Buffer
5212 r, err := interp.New(interp.StdIO(nil, &b, &b))
5213 if err != nil {
5214 t.Fatal(err)
5215 }
5216 ctx, cancel := context.WithTimeout(t.Context(), runnerRunTimeout)
5217 defer cancel()
5218 if err := r.Run(ctx, file); err != nil {
5219 t.Fatal(err)
5220 }
5221 if err := interp.BashOpts("-s", "nullglob")(r); err != nil {
5222 t.Fatal(err)
5223 }
5224 if err := r.Run(ctx, file); err != nil {
5225 t.Fatal(err)
5226 }
5227 want := "no-match-*\n\n"
5228 if got := b.String(); got != want {
5229 t.Fatalf("\nwant: %q\ngot: %q", want, got)
5230 }
5231 }
5232
5233 func TestRunnerBashOptsErr(t *testing.T) {
5234 t.Parallel()
5235
5236 tests := []struct {
5237 args []string
5238 want string
5239 }{
5240 {[]string{"-z"}, `invalid option: "-z"`},
5241 {[]string{"-p"}, `invalid option: "-p"`},
5242 {[]string{"-o", "-s", "extglob"}, `invalid option name: "extglob"`},
5243 {[]string{"-s", "pipefail"}, `invalid option name: "pipefail"`},
5244 {[]string{"extglob"}, "either -s or -u must be given to set or unset options"},
5245 {[]string{"-s", "nosuchname"}, `invalid option name: "nosuchname"`},
5246 {[]string{"-s", "login_shell"}, `unsupported option: "login_shell"`},
5247 }
5248 for _, test := range tests {
5249 t.Run("", func(t *testing.T) {
5250 _, err := interp.New(interp.BashOpts(test.args...))
5251 if err == nil {
5252 t.Fatalf("BashOpts(%q) did not error", test.args)
5253 }
5254 if got := err.Error(); got != test.want {
5255 t.Fatalf("BashOpts(%q):\nwant: %q\ngot: %q", test.args, test.want, got)
5256 }
5257 })
5258 }
5259 }
5260
5261 func TestRunnerContext(t *testing.T) {
5262 t.Parallel()
5263
5264 cases := []string{
5265 "",
5266 "while true; do true; done",
5267 "until false; do true; done",
5268 "sleep 1000",
5269 "while true; do true; done & wait",
5270 "sleep 1000 & wait",
5271 "(while true; do true; done)",
5272 "$(while true; do true; done)",
5273 "while true; do true; done | while true; do true; done",
5274 }
5275 p := syntax.NewParser()
5276 for _, in := range cases {
5277 t.Run("", func(t *testing.T) {
5278 file := parse(t, p, in)
5279 ctx, cancel := context.WithCancel(t.Context())
5280 cancel()
5281 r, _ := interp.New()
5282 errChan := make(chan error)
5283 go func() {
5284 errChan <- r.Run(ctx, file)
5285 }()
5286
5287 timeout := 500 * time.Millisecond
5288 select {
5289 case err := <-errChan:
5290 if err != nil && err != ctx.Err() {
5291 t.Fatal("Runner did not use ctx.Err()")
5292 }
5293 case <-time.After(timeout):
5294 t.Fatalf("program was not killed in %s", timeout)
5295 }
5296 })
5297 }
5298 }
5299
5300 func TestCancelBlockedStdinRead(t *testing.T) {
5301 // "read -s" reads without echoing, which must still be cancellable.
5302 for _, in := range []string{"read x", "read -s x"} {
5303 t.Run("", func(t *testing.T) { testCancelBlockedStdinRead(t, in) })
5304 }
5305 }
5306
5307 func testCancelBlockedStdinRead(t *testing.T, in string) {
5308 if runtime.GOOS == "windows" {
5309 // TODO: Why is this? The [os.File.SetReadDeadline] docs seem to imply that it should work
5310 // across all major platforms, and the file polling implementation seems to be
5311 // for all posix platforms including Windows.
5312 // Our previous logic and tests with muesli/cancelreader did not test an os.Pipe
5313 // on Windows either, so skipping here is not any worse.
5314 t.Skip("os.Pipe on windows appears to not support cancellable reads")
5315 }
5316 if runtime.GOOS == "js" {
5317 t.Skip("js/wasm has no os.Pipe, and its reads can't be cancelled")
5318 }
5319 t.Parallel()
5320
5321 p := syntax.NewParser()
5322 file := parse(t, p, in)
5323 ctx, cancel := context.WithTimeout(t.Context(), 100*time.Millisecond)
5324 // Make the linter happy, even though we deliberately wait for the timeout.
5325 defer cancel()
5326
5327 stdinRead, stdinWrite, err := os.Pipe()
5328 if err != nil {
5329 t.Fatalf("Error calling os.Pipe: %v", err)
5330 }
5331 defer func() {
5332 stdinWrite.Close()
5333 stdinRead.Close()
5334 }()
5335 r, _ := interp.New(interp.StdIO(stdinRead, nil, nil))
5336 now := time.Now()
5337 errChan := make(chan error)
5338 go func() {
5339 errChan <- r.Run(ctx, file)
5340 }()
5341
5342 timeout := 500 * time.Millisecond
5343 select {
5344 case err := <-errChan:
5345 if err == nil || err.Error() != "exit status 1" || ctx.Err() != context.DeadlineExceeded {
5346 t.Fatalf("'read x' did not timeout correctly; err: %v, ctx.Err(): %v; dur: %v",
5347 err, ctx.Err(), time.Since(now))
5348 }
5349 case <-time.After(timeout):
5350 t.Fatalf("program was not killed in %s", timeout)
5351 }
5352 }
5353
5354 func TestRunnerAltNodes(t *testing.T) {
5355 t.Parallel()
5356
5357 in := "echo foo"
5358 file := parse(t, nil, in)
5359 want := "foo\n"
5360 nodes := []syntax.Node{
5361 file,
5362 file.Stmts[0],
5363 file.Stmts[0].Cmd,
5364 }
5365 for _, node := range nodes {
5366 var cb concBuffer
5367 r, _ := interp.New(interp.StdIO(nil, &cb, &cb))
5368 ctx, cancel := context.WithTimeout(t.Context(), runnerRunTimeout)
5369 defer cancel()
5370 if err := r.Run(ctx, node); err != nil {
5371 cb.WriteString(err.Error())
5372 }
5373 if got := cb.String(); got != want {
5374 t.Fatalf("wrong output in %q:\nwant: %q\ngot: %q",
5375 in, want, got)
5376 }
5377 }
5378 }
5379
5380 func TestRunnerDir(t *testing.T) {
5381 t.Parallel()
5382
5383 wd, err := os.Getwd()
5384 if err != nil {
5385 t.Fatal(err)
5386 }
5387 t.Run("Missing", func(t *testing.T) {
5388 _, err := interp.New(interp.Dir("missing"))
5389 if err == nil {
5390 t.Fatal("expected New to error when Dir is missing")
5391 }
5392 })
5393 t.Run("NotDir", func(t *testing.T) {
5394 _, err := interp.New(interp.Dir("interp_test.go"))
5395 if err == nil {
5396 t.Fatal("expected New to error when Dir is not a dir")
5397 }
5398 })
5399 t.Run("NotDirAbs", func(t *testing.T) {
5400 _, err := interp.New(interp.Dir(filepath.Join(wd, "interp_test.go")))
5401 if err == nil {
5402 t.Fatal("expected New to error when Dir is not a dir")
5403 }
5404 })
5405 t.Run("Relative", func(t *testing.T) {
5406 // On Windows, it's impossible to make a relative path from one
5407 // drive to another. Use the parent directory, as that's for
5408 // sure in the same drive as the current directory.
5409 rel := ".." + string(filepath.Separator)
5410 r, err := interp.New(interp.Dir(rel))
5411 if err != nil {
5412 t.Fatal(err)
5413 }
5414 if !filepath.IsAbs(r.Dir) {
5415 t.Errorf("Runner.Dir is not absolute")
5416 }
5417 })
5418 // Ensure that we treat symlinks and short paths properly, especially
5419 // with Dir and globbing.
5420 t.Run("SymlinkOrShortPath", func(t *testing.T) {
5421 tdir := t.TempDir()
5422
5423 realDir := filepath.Join(tdir, "real-long-dir-name")
5424 realFile := filepath.Join(realDir, "realfile")
5425
5426 if err := os.Mkdir(realDir, 0o777); err != nil {
5427 t.Fatal(err)
5428 }
5429 if err := os.WriteFile(realFile, []byte(""), 0o666); err != nil {
5430 t.Fatal(err)
5431 }
5432
5433 var altDir string
5434 if runtime.GOOS == "windows" {
5435 short, err := shortPathName(realDir)
5436 if err != nil {
5437 t.Fatal(err)
5438 }
5439 altDir = short
5440 // We replace tdir later, and it might have been shortened.
5441 tdir = filepath.Dir(altDir)
5442 } else {
5443 altDir = filepath.Join(tdir, "symlink")
5444 if err := os.Symlink(realDir, altDir); err != nil {
5445 t.Fatal(err)
5446 }
5447 }
5448
5449 var b bytes.Buffer
5450 r, err := interp.New(interp.Dir(altDir), interp.StdIO(nil, &b, &b))
5451 if err != nil {
5452 t.Fatal(err)
5453 }
5454 file := parse(t, nil, "echo $PWD $PWD/*")
5455 ctx, cancel := context.WithTimeout(t.Context(), runnerRunTimeout)
5456 defer cancel()
5457 if err := r.Run(ctx, file); err != nil {
5458 t.Fatal(err)
5459 }
5460 got := b.String()
5461 got = strings.ReplaceAll(got, tdir, "")
5462 got = strings.TrimSpace(got)
5463 want := `/symlink /symlink/realfile`
5464 if runtime.GOOS == "windows" {
5465 want = `\\REAL.{4} \\REAL.{4}\\realfile`
5466 }
5467 if !regexp.MustCompile(want).MatchString(got) {
5468 t.Fatalf("\nwant regexp: %q\ngot: %q", want, got)
5469 }
5470 })
5471 }
5472
5473 func TestRunnerIncremental(t *testing.T) {
5474 t.Parallel()
5475
5476 file := parse(t, nil, "echo foo; false; echo bar; exit 0; echo baz")
5477 want := "foo\nbar\n"
5478 var b bytes.Buffer
5479 r, _ := interp.New(interp.StdIO(nil, &b, &b))
5480 ctx, cancel := context.WithTimeout(t.Context(), runnerRunTimeout)
5481 defer cancel()
5482 for _, stmt := range file.Stmts {
5483 err := r.Run(ctx, stmt)
5484 if _, ok := errors.AsType[interp.ExitStatus](err); !ok && err != nil {
5485 // Keep track of unexpected errors.
5486 b.WriteString(err.Error())
5487 }
5488 if r.Exited() {
5489 break
5490 }
5491 }
5492 if got := b.String(); got != want {
5493 t.Fatalf("\nwant: %q\ngot: %q", want, got)
5494 }
5495 }
5496
5497 func TestRunnerIncrementalExitTrap(t *testing.T) {
5498 t.Parallel()
5499
5500 file := parse(t, nil, "trap 'echo bye' EXIT\necho a\necho b\nexit 3\necho never")
5501 want := "a\nb\nbye\n"
5502 var b bytes.Buffer
5503 r, _ := interp.New(interp.StdIO(nil, &b, &b))
5504 ctx, cancel := context.WithTimeout(t.Context(), runnerRunTimeout)
5505 defer cancel()
5506 var exit interp.ExitStatus
5507 for _, stmt := range file.Stmts {
5508 err := r.Run(ctx, stmt)
5509 if es, ok := errors.AsType[interp.ExitStatus](err); ok {
5510 exit = es
5511 } else if err != nil {
5512 b.WriteString(err.Error())
5513 }
5514 if r.Exited() {
5515 break
5516 }
5517 }
5518 if exit != 3 {
5519 t.Fatalf("want exit status 3, got %d", exit)
5520 }
5521 if got := b.String(); got != want {
5522 t.Fatalf("\nwant: %q\ngot: %q", want, got)
5523 }
5524 }
5525
5526 func TestRunnerResetFields(t *testing.T) {
5527 t.Parallel()
5528
5529 tdir := t.TempDir()
5530 logPath := filepath.Join(tdir, "log")
5531 logFile, err := os.Create(logPath)
5532 if err != nil {
5533 t.Fatal(err)
5534 }
5535 defer logFile.Close()
5536 r, _ := interp.New(
5537 interp.Params("-f", "--", "first", tdir, logPath),
5538 interp.Dir(tdir),
5539 interp.ExecHandlers(testExecHandler),
5540 )
5541 // Check that using option funcs and Runner fields directly is still
5542 // kept by Reset.
5543 interp.StdIO(nil, logFile, os.Stderr)(r)
5544 r.Env = expand.ListEnviron(append(os.Environ(), "GLOBAL=foo")...)
5545
5546 file := parse(t, nil, `
5547 # Params set 3 arguments
5548 [[ $# -eq 3 ]] || exit 10
5549 [[ $1 == "first" ]] || exit 11
5550
5551 # Params set the -f option (noglob)
5552 [[ -o noglob ]] || exit 12
5553
5554 # $PWD was set via Dir, and should be equal to $2
5555 [[ "$PWD" == "$2" ]] || exit 13
5556
5557 # stdout should go into the log file, which is at $3
5558 echo line1
5559 echo line2
5560 [[ "$(wc -l <$3)" == "2" ]] || exit 14
5561
5562 # $GLOBAL was set directly via the Env field
5563 [[ "$GLOBAL" == "foo" ]] || exit 15
5564
5565 # Change all of the above within the script. Reset should undo this.
5566 set +f -- newargs
5567 cd
5568 exec >/dev/null 2>/dev/null
5569 GLOBAL=
5570 export GLOBAL=
5571 `)
5572 ctx, cancel := context.WithTimeout(t.Context(), runnerRunTimeout)
5573 defer cancel()
5574 for i := range 3 {
5575 if err := r.Run(ctx, file); err != nil {
5576 t.Fatalf("run number %d: %v", i, err)
5577 }
5578 r.Reset()
5579 // empty the log file too
5580 logFile.Truncate(0)
5581 logFile.Seek(0, io.SeekStart)
5582 }
5583 }
5584
5585 func TestRunnerManyResets(t *testing.T) {
5586 t.Parallel()
5587 r, _ := interp.New()
5588 for range 5 {
5589 r.Reset()
5590 }
5591 }
5592
5593 func TestRunnerFilename(t *testing.T) {
5594 t.Parallel()
5595
5596 want := "f.sh\n"
5597 file, _ := syntax.NewParser().Parse(strings.NewReader("echo $0"), "f.sh")
5598 var b bytes.Buffer
5599 r, _ := interp.New(interp.StdIO(nil, &b, &b))
5600 ctx, cancel := context.WithTimeout(t.Context(), runnerRunTimeout)
5601 defer cancel()
5602 if err := r.Run(ctx, file); err != nil {
5603 t.Fatal(err)
5604 }
5605 if got := b.String(); got != want {
5606 t.Fatalf("\nwant: %q\ngot: %q", want, got)
5607 }
5608 }
5609
5610 func TestRunnerEnvNoModify(t *testing.T) {
5611 t.Parallel()
5612
5613 env := expand.ListEnviron("one=1", "two=2")
5614 file := parse(t, nil, `echo -n "$one $two; "; one=x; unset two`)
5615
5616 var b bytes.Buffer
5617 r, _ := interp.New(interp.Env(env), interp.StdIO(nil, &b, &b))
5618 ctx, cancel := context.WithTimeout(t.Context(), runnerRunTimeout)
5619 defer cancel()
5620 for range 3 {
5621 r.Reset()
5622 err := r.Run(ctx, file)
5623 if err != nil {
5624 t.Fatal(err)
5625 }
5626 }
5627
5628 want := "1 2; 1 2; 1 2; "
5629 if got := b.String(); got != want {
5630 t.Fatalf("\nwant: %q\ngot: %q", want, got)
5631 }
5632 }
5633
5634 func TestRunnerASTNoModify(t *testing.T) {
5635 t.Parallel()
5636
5637 file := parse(t, nil, "shopt -s expand_aliases; alias foo=echo\nfoo bar")
5638 printer := syntax.NewPrinter()
5639 var sb strings.Builder
5640 printer.Print(&sb, file)
5641 before := sb.String()
5642
5643 var b bytes.Buffer
5644 r, _ := interp.New(interp.StdIO(nil, &b, &b))
5645 ctx, cancel := context.WithTimeout(t.Context(), runnerRunTimeout)
5646 defer cancel()
5647 if err := r.Run(ctx, file); err != nil {
5648 t.Fatal(err)
5649 }
5650 if want := "bar\n"; b.String() != want {
5651 t.Fatalf("want output %q, got %q", want, b.String())
5652 }
5653
5654 sb.Reset()
5655 printer.Print(&sb, file)
5656 after := sb.String()
5657 if after != before {
5658 t.Fatalf("Run modified the AST:\nbefore: %q\nafter: %q", before, after)
5659 }
5660 }
5661
5662 func TestMalformedPathOnWindows(t *testing.T) {
5663 if runtime.GOOS != "windows" {
5664 t.Skip("Skipping windows test on non-windows GOOS")
5665 }
5666 tdir := t.TempDir()
5667 t.Parallel()
5668
5669 path := filepath.Join(tdir, "test.cmd")
5670 script := []byte("@echo foo")
5671 if err := os.WriteFile(path, script, 0o777); err != nil {
5672 t.Fatal(err)
5673 }
5674
5675 // set PATH to c:\tmp\dir instead of C:\tmp\dir
5676 volume := filepath.VolumeName(tdir)
5677 pathList := strings.ToLower(volume) + tdir[len(volume):]
5678
5679 file := parse(t, nil, "test.cmd")
5680 var cb concBuffer
5681 r, _ := interp.New(interp.Env(expand.ListEnviron("PATH="+pathList)), interp.StdIO(nil, &cb, &cb))
5682 ctx, cancel := context.WithTimeout(t.Context(), runnerRunTimeout)
5683 defer cancel()
5684 if err := r.Run(ctx, file); err != nil {
5685 t.Fatal(err)
5686 }
5687 want := "foo\r\n"
5688 if got := cb.String(); got != want {
5689 t.Fatalf("wrong output:\nwant: %q\ngot: %q", want, got)
5690 }
5691 }
5692
5693 func TestReadShouldNotPanicWithNilStdin(t *testing.T) {
5694 t.Parallel()
5695
5696 r, err := interp.New()
5697 if err != nil {
5698 t.Fatal(err)
5699 }
5700
5701 f := parse(t, nil, "read foobar")
5702 ctx, cancel := context.WithTimeout(t.Context(), runnerRunTimeout)
5703 defer cancel()
5704 if err := r.Run(ctx, f); err == nil {
5705 t.Fatal("it should have returned an error")
5706 }
5707 }
5708
5709 func TestRunnerVars(t *testing.T) {
5710 t.Parallel()
5711
5712 r, err := interp.New()
5713 if err != nil {
5714 t.Fatal(err)
5715 }
5716
5717 f := parse(t, nil, "foo=updated; BAR=new")
5718 ctx, cancel := context.WithTimeout(t.Context(), runnerRunTimeout)
5719 defer cancel()
5720 if err := r.Run(ctx, f); err != nil {
5721 t.Fatal(err)
5722 }
5723
5724 if want, got := "updated", r.Vars["foo"].String(); got != want {
5725 t.Fatalf("wrong output:\nwant: %q\ngot: %q", want, got)
5726 }
5727 }
5728
5729 func TestRunnerSubshell(t *testing.T) {
5730 t.Parallel()
5731
5732 r1, err := interp.New()
5733 if err != nil {
5734 t.Fatal(err)
5735 }
5736
5737 r2 := r1.Subshell()
5738 f1 := parse(t, nil, "PARENT=foo")
5739 f2 := parse(t, nil, "CHILD=bar")
5740
5741 ctx, cancel := context.WithTimeout(t.Context(), runnerRunTimeout)
5742 defer cancel()
5743 if err := r1.Run(ctx, f1); err != nil {
5744 t.Fatal(err)
5745 }
5746 if err := r2.Run(ctx, f2); err != nil {
5747 t.Fatal(err)
5748 }
5749
5750 if want, got := "foo", r1.Vars["PARENT"].String(); got != want {
5751 t.Fatalf("wrong output:\nwant: %q\ngot: %q", want, got)
5752 }
5753 if want, got := "bar", r2.Vars["CHILD"].String(); got != want {
5754 t.Fatalf("wrong output:\nwant: %q\ngot: %q", want, got)
5755 }
5756
5757 r3 := r2.Subshell()
5758 f3 := parse(t, nil, "CHILD=modified")
5759 if err := r3.Run(ctx, f3); err != nil {
5760 t.Fatal(err)
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 if want, got := "modified", r3.Vars["CHILD"].String(); got != want {
5766 t.Fatalf("wrong output:\nwant: %q\ngot: %q", want, got)
5767 }
5768 }
5769
5770 func TestRunnerNonFileStdin(t *testing.T) {
5771 const src = "while read a; do echo $a; GOSH_CMD=print_ok $GOSH_PROG; done"
5772 skipIfUnsupported(t, src)
5773 t.Parallel()
5774
5775 var cb concBuffer
5776 r, err := interp.New(interp.StdIO(strings.NewReader("a\nb\nc\n"), &cb, &cb))
5777 if err != nil {
5778 t.Fatal(err)
5779 }
5780 file := parse(t, nil, src)
5781 ctx, cancel := context.WithTimeout(t.Context(), runnerRunTimeout)
5782 defer cancel()
5783 if err := r.Run(ctx, file); err != nil {
5784 cb.WriteString(err.Error())
5785 }
5786 // TODO: just like with heredocs, the first print_ok call consumes all stdin.
5787 qt.Assert(t, qt.Equals(cb.String(), "a\nexec ok\nb\nexec ok\nc\nexec ok\n"))
5788 }