Skip to main content

shell/bash/
mod.rs

1//! The Bash shell implementation.
2//!
3//! The Shell layer is split into a shared execution core
4//! ([`ShellCore`](crate::core::ShellCore)) and per-shell shells. Bash is
5//! one of them: it owns its grammar (via [`brush_parser`]), its builtin
6//! table, and its dialect (messages and prompt). Builtins it shares with
7//! Zsh delegate to core mechanisms only where the two shells were verified
8//! to behave identically (`cd`, `pwd`, `jobs`, `fg`, `bg`, `hash`, `dirs`,
9//! `pushd`, `popd`, `unset`, `source`, `clear`); anything with different
10//! semantics (`echo`, `export`, `alias`, `type`) is implemented here.
11//!
12//! Parsing uses the [`brush_parser`] crate — the tokenizer and AST parser
13//! from the brush-shell project — so shell grammar (quoting, operators,
14//! pipelines, compound commands) is real grammar, not a hand-rolled
15//! approximation.
16//!
17//! Supported compound constructs: `if`/`elif`/`else`, `while`/`until`,
18//! brace groups, subshells (isolated session state), `for` iteration,
19//! `case` clauses, arithmetic (`$(( ))` and `(( ))`, sharing one evaluator
20//! with the expander), function definitions, and `[[ ]]` extended tests.
21//! Arrays are not supported yet.
22
23use engine::{Input, Output, Terminal, VirtualPath};
24use os::{Credentials, ExitStatus, UnixOs};
25
26use crate::core::{ShellCore, ShellDialect};
27
28/// The Bash shell.
29pub struct Bash<'os> {
30    /// The shared execution core in the Bash dialect.
31    core: ShellCore<'os>,
32}
33
34impl<'os> Bash<'os> {
35    /// Creates a Bash shell for a session.
36    pub fn new(os: &'os UnixOs, credentials: Credentials) -> Result<Self, os::OsError> {
37        let mut core = ShellCore::new(os, credentials, bash_dialect())?;
38        // Scripts run through this shell, not a separate interpreter.
39        core.install_shell_bindings();
40        // Startup files define the session's aliases and functions.
41        core.source_startup_files();
42        Ok(Self { core })
43    }
44}
45
46/// The behavior of `/bin/sh` and `/bin/bash`: the Bash dialect as a
47/// program. Scripts and `sh -c` invocations run through the same
48/// implementation as interactive commands.
49pub struct BashInterpreter;
50
51impl os::runtime::Command for BashInterpreter {
52    fn name(&self) -> &'static str {
53        "bash"
54    }
55
56    fn execute(
57        &self,
58        context: &mut os::runtime::CommandContext<'_, '_, '_, '_>,
59    ) -> Result<os::runtime::ExitStatus, os::OsError> {
60        crate::core::run_interpreter_invocation(
61            context.os,
62            context.credentials.clone(),
63            bash_dialect(),
64            context.cwd,
65            context.argv,
66            &mut *context.stdin,
67            &mut *context.stdout,
68            &mut *context.stderr,
69        )
70    }
71}
72
73/// The Bash dialect: identity, messages, and the builtin table.
74/// The Bash dialect, also used for non-interactive interpreter invocations
75/// (`/bin/sh`, `/bin/bash`): the shell grammar this project implements.
76pub(crate) fn bash_dialect() -> ShellDialect {
77    ShellDialect {
78        name: "bash",
79        command_not_found: |name| format!("bash: {name}: command not found\n"),
80        run_builtin: bash_run_builtin,
81        system_rc: "/etc/bashrc",
82        user_rc: ".bashrc",
83        echo_escapes_default: false,
84        export_prefix: "declare -x ",
85        alias_prefix: "alias ",
86    }
87}
88
89/// Whether a name is a Bash builtin.
90fn bash_is_builtin(name: &str) -> bool {
91    matches!(
92        name,
93        "cd" | "pwd"
94            | "export"
95            | "history"
96            | "alias"
97            | "unalias"
98            | "jobs"
99            | "fg"
100            | "bg"
101            | "wait"
102            | "hash"
103            | "echo"
104            | "clear"
105            | ":"
106            | "dirs"
107            | "pushd"
108            | "popd"
109            | "unset"
110            | "source"
111            | "."
112            | "type"
113            | "exit"
114    )
115}
116
117/// Dispatches a Bash builtin (function → builtin → external).
118fn bash_run_builtin(
119    core: &mut ShellCore,
120    name: &str,
121    argv: &[String],
122    stdin: &mut dyn Input,
123    stdout: &mut dyn Output,
124    stderr: &mut dyn Output,
125) -> Option<ExitStatus> {
126    let status = match name {
127        // Shared mechanisms, verified identical in Bash and Zsh.
128        "cd" => core.cd_to(argv, stdout, stderr),
129        "pwd" => core.pwd_of(stdout),
130        "jobs" => core.list_jobs(stdout),
131        "fg" => core.foreground_job(argv, stdout, stderr),
132        "bg" => core.background_job(argv, stdout, stderr),
133        "wait" => core.wait_for_jobs(argv, stderr),
134        "hash" => core.hash_table(argv, stdout, stderr),
135        "dirs" => core.print_dirs(stdout),
136        "pushd" => core.push_directory(argv, stdout, stderr),
137        "popd" => core.pop_directory(argv, stdout, stderr),
138        "unset" => core.unset_names(argv, stderr),
139        "source" | "." => core.source_file(argv, stdin, stdout, stderr),
140        "clear" => core.clear_screen(stdout),
141        ":" => core.null_command(),
142        // Bash-owned semantics on shared mechanisms (the dialect carries
143        // the phrasing).
144        "echo" => core.builtin_echo(argv, stdout),
145        "export" => core.builtin_export(argv, stdout, stderr),
146        "history" => core.builtin_history(stdout),
147        "alias" => core.builtin_alias(argv, stdout, stderr),
148        "unalias" => core.builtin_unalias(argv, stderr),
149        "type" => bash_type(core, argv, stdout, stderr),
150        "exit" => core.request_exit(argv.get(1).map(String::as_str)),
151        _ => return None,
152    };
153    Some(status)
154}
155
156/// The Bash `type` builtin: reports how a name would be resolved.
157fn bash_type(
158    core: &mut ShellCore,
159    argv: &[String],
160    stdout: &mut dyn Output,
161    stderr: &mut dyn Output,
162) -> ExitStatus {
163    let mut exit_status = ExitStatus::SUCCESS;
164    for name in argv.iter().skip(1) {
165        let resolution = core.resolve_name(name, bash_is_builtin);
166        if let Some(alias) = resolution.alias {
167            let _ = stdout.write(format!("{name} is aliased to `{alias}'\n").as_bytes());
168            continue;
169        }
170        if resolution.function {
171            let _ = stdout.write(format!("{name} is a function\n").as_bytes());
172            continue;
173        }
174        if resolution.builtin {
175            let _ = stdout.write(format!("{name} is a shell builtin\n").as_bytes());
176            continue;
177        }
178        if let Some(path) = resolution.paths.into_iter().next() {
179            let _ = stdout.write(format!("{name} is {path}\n").as_bytes());
180        } else {
181            exit_status = ExitStatus::FAILURE;
182            let _ = stderr.write(format!("bash: type: {name}: not found\n").as_bytes());
183        }
184    }
185    exit_status
186}
187
188impl<'os> crate::Shell for Bash<'os> {
189    fn name(&self) -> &'static str {
190        "bash"
191    }
192
193    fn actor(&self) -> engine::ActorId {
194        self.core.credentials().actor()
195    }
196
197    fn environment(&self) -> &os::Environment {
198        self.core.environment()
199    }
200
201    fn engine(&self) -> &engine::Engine {
202        self.core.os().engine()
203    }
204
205    fn boot_time(&self) -> engine::Timestamp {
206        self.core.os().boot_time()
207    }
208
209    fn hostname(&self) -> String {
210        crate::core::hostname_from_etc(self.core.os())
211    }
212
213    fn cwd(&self) -> &VirtualPath {
214        self.core.cwd()
215    }
216
217    fn prompt(&self, hostname: &str) -> String {
218        format!(
219            "{}@{}:{}> ",
220            self.core.credentials().username(),
221            hostname,
222            self.core.cwd()
223        )
224    }
225
226    fn banner(&self) -> Option<String> {
227        Some(format!(
228            "Last login: {} on ttys000\n",
229            crate::core::format_login_line(self.core.os().boot_time())
230        ))
231    }
232
233    fn set_terminal_size(&mut self, rows: u16, cols: u16) {
234        self.core.set_terminal_size(rows, cols);
235    }
236
237    fn execute(
238        &mut self,
239        line: &str,
240        stdin: &mut dyn Input,
241        stdout: &mut dyn Output,
242        stderr: &mut dyn Output,
243    ) -> ExitStatus {
244        self.core.execute(line, stdin, stdout, stderr)
245    }
246
247    fn execute_with_terminal(
248        &mut self,
249        line: &str,
250        stdin: &mut dyn Input,
251        stdout: &mut dyn Output,
252        stderr: &mut dyn Output,
253        terminal: Option<&mut dyn Terminal>,
254    ) -> ExitStatus {
255        self.core
256            .execute_with_terminal(line, stdin, stdout, stderr, terminal)
257    }
258
259    fn take_exit_status(&mut self) -> Option<ExitStatus> {
260        self.core.take_exit_request()
261    }
262
263    fn history(&self) -> &[String] {
264        self.core.history()
265    }
266
267    fn record_history(&mut self, line: &str) {
268        self.core.record_history(line);
269    }
270
271    fn needs_continuation(&self, input: &str) -> bool {
272        crate::core::needs_continuation(input)
273    }
274}
275
276#[cfg(test)]
277mod tests {
278    use super::*;
279    use crate::Shell;
280    use crate::core::needs_continuation;
281    use engine::{BytesInput, BytesOutput, Timestamp};
282    use os::HostIdentity;
283    use os::linux::Linux;
284
285    fn test_shell() -> Bash<'static> {
286        // Leak the Linux to get a 'static reference for test convenience.
287        let linux = Box::leak(Box::new(
288            Linux::with_identity(
289                &HostIdentity::new("demo", "demo-host"),
290                Timestamp::from_nanos(1_000_000),
291            )
292            .unwrap(),
293        ));
294        let credentials = linux
295            .unix()
296            .users()
297            .authenticate("demo", "demo", linux.unix().groups())
298            .unwrap();
299        Bash::new(linux.unix(), credentials).unwrap()
300    }
301
302    /// Runs a line, returning (status, stdout).
303    fn run(shell: &mut Bash<'static>, line: &str) -> (ExitStatus, Vec<u8>, Vec<u8>) {
304        let mut stdin = BytesInput::new(b"");
305        let mut stdout = BytesOutput::new();
306        let mut stderr = BytesOutput::new();
307        let status = shell.execute(line, &mut stdin, &mut stdout, &mut stderr);
308        (status, stdout.into_bytes(), stderr.into_bytes())
309    }
310
311    #[test]
312    fn builtin_cd_and_pwd() {
313        let mut shell = test_shell();
314        assert_eq!(run(&mut shell, "mkdir /tmp/testdir").0, ExitStatus::SUCCESS);
315        let (status, _, _) = run(&mut shell, "cd /tmp/testdir");
316        assert_eq!(status, ExitStatus::SUCCESS);
317        assert_eq!(shell.cwd().to_string(), "/tmp/testdir");
318        let (_, out, _) = run(&mut shell, "pwd");
319        assert_eq!(out, b"/tmp/testdir\n");
320    }
321
322    #[test]
323    fn external_ls_and_which() {
324        let mut shell = test_shell();
325        let (status, out, _) = run(&mut shell, "which ls");
326        assert_eq!(status, ExitStatus::SUCCESS);
327        assert_eq!(out, b"/usr/bin/ls\n");
328
329        let (status, out, _) = run(&mut shell, "ls /");
330        assert_eq!(status, ExitStatus::SUCCESS);
331        let output = String::from_utf8(out).unwrap();
332        assert!(output.contains("bin"));
333        assert!(output.contains("etc"));
334    }
335
336    #[test]
337    fn redirection_and_cat() {
338        let mut shell = test_shell();
339        let (status, out, _) = run(&mut shell, "echo hello > /tmp/hello.txt");
340        assert_eq!(status, ExitStatus::SUCCESS);
341        // Redirection must not leak to the caller's stdout.
342        assert_eq!(out, b"");
343        let (status, out, _) = run(&mut shell, "cat /tmp/hello.txt");
344        assert_eq!(status, ExitStatus::SUCCESS);
345        assert_eq!(out, b"hello\n");
346    }
347
348    #[test]
349    fn single_quotes_do_not_expand() {
350        let mut shell = test_shell();
351        let (_, out, _) = run(&mut shell, "echo '$HOME'");
352        assert_eq!(out, b"$HOME\n");
353    }
354
355    #[test]
356    fn double_quotes_expand_but_do_not_split() {
357        let mut shell = test_shell();
358        let (_, out, _) = run(&mut shell, "echo \"$HOME/x y\"");
359        assert_eq!(out, b"/home/demo/x y\n");
360    }
361
362    #[test]
363    fn quoted_operators_are_not_operators() {
364        let mut shell = test_shell();
365        let (status, out, _) = run(&mut shell, "echo \"a & b; c\"");
366        assert_eq!(status, ExitStatus::SUCCESS);
367        assert_eq!(out, b"a & b; c\n");
368    }
369
370    #[test]
371    fn and_or_sequencing_preserves_quoting() {
372        let mut shell = test_shell();
373        let (status, out, _) = run(
374            &mut shell,
375            "echo 'first word' > /tmp/q.txt && cat /tmp/q.txt",
376        );
377        assert_eq!(status, ExitStatus::SUCCESS);
378        assert_eq!(out, b"first word\n");
379    }
380
381    #[test]
382    fn background_ampersand_is_recorded() {
383        let mut shell = test_shell();
384        // Both commands run; the backgrounded one is recorded as a job.
385        let (_, out, _) = run(&mut shell, "echo backgrounded & echo foreground");
386        assert_eq!(out, b"backgrounded\nforeground\n");
387        let (_, jobs, _) = run(&mut shell, "jobs");
388        assert!(String::from_utf8_lossy(&jobs).contains("echo backgrounded"));
389    }
390
391    #[test]
392    fn arithmetic_expansion_evaluates() {
393        let mut shell = test_shell();
394        let (_, out, _) = run(&mut shell, "echo $((1 + 1))");
395        assert_eq!(out, b"2\n");
396        // Precedence and grouping.
397        let (_, out, _) = run(&mut shell, "echo $((2 + 3 * 4))");
398        assert_eq!(out, b"14\n");
399        let (_, out, _) = run(&mut shell, "echo $(((2 + 3) * 4))");
400        assert_eq!(out, b"20\n");
401        // Variables are references; assignment operators mutate them.
402        run(&mut shell, "count=5");
403        let (_, out, _) = run(&mut shell, "echo $((count * 2))");
404        assert_eq!(out, b"10\n");
405        run(&mut shell, "((count += 3))");
406        let (_, out, _) = run(&mut shell, "echo $count");
407        assert_eq!(out, b"8\n");
408        // Substitution inside the expression.
409        let (_, out, _) = run(&mut shell, "echo $(($(grep -c . /dev/null) + 7))");
410        assert_eq!(out, b"7\n");
411    }
412
413    #[test]
414    fn arithmetic_command_reports_nonzero_as_success() {
415        let mut shell = test_shell();
416        let (status, _, _) = run(&mut shell, "((1 + 1))");
417        assert_eq!(status, ExitStatus::SUCCESS);
418        let (status, _, _) = run(&mut shell, "((1 - 1))");
419        assert_eq!(status.code(), 1);
420    }
421
422    #[test]
423    fn case_clause_matches_patterns_in_order() {
424        let mut shell = test_shell();
425        let (_, out, _) = run(
426            &mut shell,
427            "case /etc/passwd in /etc/*) echo system ;; *) echo other ;; esac",
428        );
429        assert_eq!(out, b"system\n");
430        // No match at all succeeds.
431        let (status, out, _) = run(&mut shell, "case zzz in aaa) echo a ;; esac");
432        assert_eq!(status, ExitStatus::SUCCESS);
433        assert_eq!(out, b"");
434        // First matching branch wins.
435        let (_, out, _) = run(
436            &mut shell,
437            "case abc in a*) echo one ;; *) echo two ;; esac",
438        );
439        assert_eq!(out, b"one\n");
440    }
441
442    #[test]
443    fn subshell_isolates_state() {
444        let mut shell = test_shell();
445        run(&mut shell, "cd /tmp && mkdir -p /tmp/subshell-test");
446        // Variable changes, cd, and exit do not escape the subshell.
447        let (status, out, _) = run(
448            &mut shell,
449            "(value=inner; cd /tmp/subshell-test); echo $value; pwd",
450        );
451        assert_eq!(status, ExitStatus::SUCCESS);
452        assert_eq!(out, b"\n/tmp\n");
453        // The subshell's own output and status propagate.
454        let (status, out, _) = run(&mut shell, "(false || echo recovered)");
455        assert_eq!(status, ExitStatus::SUCCESS);
456        assert_eq!(out, b"recovered\n");
457    }
458
459    #[test]
460    fn bang_negates_pipeline_status() {
461        let mut shell = test_shell();
462        run(&mut shell, "echo x > /tmp/real_file.txt");
463        let (status, _, _) = run(&mut shell, "! cat /tmp/real_file.txt");
464        assert_eq!(status, ExitStatus::FAILURE, "! <success> fails");
465        let (status, _, _) = run(&mut shell, "! cat /tmp/none");
466        assert_eq!(status, ExitStatus::SUCCESS, "! <failure> succeeds");
467    }
468
469    #[test]
470    fn if_elif_else_executes() {
471        let mut shell = test_shell();
472        run(&mut shell, "echo yes > /tmp/marker.txt");
473        let (status, out, _) = run(
474            &mut shell,
475            "if cat /tmp/marker.txt; then echo branch-then; elif cat /tmp/none; then echo branch-elif; else echo branch-else; fi",
476        );
477        assert_eq!(status, ExitStatus::SUCCESS);
478        assert_eq!(out, b"yes\nbranch-then\n");
479
480        let (status, out, _) = run(
481            &mut shell,
482            "if cat /tmp/none; then echo branch-then; elif cat /tmp/marker.txt; then echo branch-elif; else echo branch-else; fi",
483        );
484        // `cat /tmp/marker.txt` prints the marker, then the elif body runs.
485        assert_eq!(status, ExitStatus::SUCCESS);
486        assert_eq!(out, b"yes\nbranch-elif\n");
487
488        let (status, out, _) = run(
489            &mut shell,
490            "if cat /tmp/none; then echo branch-then; else echo branch-else; fi",
491        );
492        assert_eq!(status, ExitStatus::SUCCESS);
493        assert_eq!(out, b"branch-else\n");
494    }
495
496    #[test]
497    fn while_loops_until_the_condition_fails() {
498        let mut shell = test_shell();
499        // A loop over real state: run while the guard file exists, removing
500        // it in the body, so the loop runs exactly once.
501        run(&mut shell, "echo guard > /tmp/loop_guard.txt");
502        let (status, _, _) = run(
503            &mut shell,
504            "while cat /tmp/loop_guard.txt; do rm /tmp/loop_guard.txt; done",
505        );
506        assert_eq!(status, ExitStatus::SUCCESS);
507        let (status, _, _) = run(&mut shell, "cat /tmp/loop_guard.txt");
508        assert_eq!(
509            status,
510            ExitStatus::FAILURE,
511            "the loop body removed the guard"
512        );
513    }
514
515    #[test]
516    fn functions_are_defined_and_called() {
517        let mut shell = test_shell();
518        let (status, _, _) = run(&mut shell, "greet() { echo hello; }");
519        assert_eq!(status, ExitStatus::SUCCESS);
520        let (status, out, _) = run(&mut shell, "greet");
521        assert_eq!(status, ExitStatus::SUCCESS);
522        assert_eq!(out, b"hello\n");
523    }
524
525    #[test]
526    fn assignments_prefix_the_command_environment() {
527        let mut shell = test_shell();
528        // With PATH=/bin, `which ls` reports the path exactly as
529        // constructed from the PATH entry, like real GNU which on a
530        // merged-/usr system.
531        let (status, out, _) = run(&mut shell, "PATH=/bin which ls");
532        assert_eq!(status, ExitStatus::SUCCESS);
533        assert_eq!(out, b"/bin/ls\n");
534    }
535
536    #[test]
537    fn bare_assignments_persist_in_the_shell() {
538        let mut shell = test_shell();
539        let (status, _, _) = run(&mut shell, "MYVAR=hello");
540        assert_eq!(status, ExitStatus::SUCCESS);
541        assert_eq!(shell.environment().get("MYVAR"), Some("hello"));
542        let (_, out, _) = run(&mut shell, "echo $MYVAR");
543        assert_eq!(out, b"hello\n");
544    }
545
546    #[test]
547    fn heredoc_feeds_stdin() {
548        let mut shell = test_shell();
549        let (status, out, _) = run(&mut shell, "cat <<EOF\nhello heredoc\nEOF");
550        assert_eq!(status, ExitStatus::SUCCESS);
551        assert_eq!(out, b"hello heredoc\n");
552    }
553
554    #[test]
555    fn pipeline_pipes_output() {
556        let mut shell = test_shell();
557        run(&mut shell, "echo hello > /tmp/a.txt");
558        let (status, out, _) = run(&mut shell, "cat /tmp/a.txt | cat");
559        assert_eq!(status, ExitStatus::SUCCESS);
560        assert_eq!(out, b"hello\n");
561    }
562
563    #[test]
564    fn globs_expand_unquoted_stars() {
565        let mut shell = test_shell();
566        run(&mut shell, "echo a > /tmp/glob_a.txt");
567        run(&mut shell, "echo b > /tmp/glob_b.txt");
568        let (status, out, _) = run(&mut shell, "echo /tmp/glob_*.txt");
569        assert_eq!(status, ExitStatus::SUCCESS);
570        let output = String::from_utf8(out).unwrap();
571        assert!(output.contains("glob_a.txt"));
572        assert!(output.contains("glob_b.txt"));
573        // Quoted globs stay literal.
574        let (_, out, _) = run(&mut shell, "echo '/tmp/glob_*.txt'");
575        assert_eq!(out, b"/tmp/glob_*.txt\n");
576    }
577
578    #[test]
579    fn mv_overwrites_existing_files() {
580        let mut shell = test_shell();
581        run(&mut shell, "echo one > /tmp/a.txt");
582        run(&mut shell, "echo two > /tmp/b.txt");
583        let (status, _, _) = run(&mut shell, "mv /tmp/a.txt /tmp/b.txt");
584        assert_eq!(status, ExitStatus::SUCCESS);
585        let (_, out, _) = run(&mut shell, "cat /tmp/b.txt");
586        assert_eq!(out, b"one\n");
587        let (status, _, _) = run(&mut shell, "cat /tmp/a.txt");
588        assert_eq!(status, ExitStatus::FAILURE);
589    }
590
591    #[test]
592    fn scripts_run_through_the_interpreter() {
593        let mut shell = test_shell();
594        run(
595            &mut shell,
596            "echo 'echo hello > /tmp/script_out.txt' > /tmp/script.sh",
597        );
598        let (status, _, _) = run(&mut shell, "sh /tmp/script.sh");
599        assert_eq!(status, ExitStatus::SUCCESS);
600        let (_, out, _) = run(&mut shell, "cat /tmp/script_out.txt");
601        assert_eq!(out, b"hello\n");
602    }
603
604    #[test]
605    fn exit_carries_a_status_and_requests_session_end() {
606        let mut shell = test_shell();
607        assert!(shell.take_exit_status().is_none());
608        let (status, _, _) = run(&mut shell, "exit 7");
609        assert_eq!(status, ExitStatus::new(7));
610        assert_eq!(shell.take_exit_status(), Some(ExitStatus::new(7)));
611        // The request is consumed: a second poll sees none.
612        assert!(shell.take_exit_status().is_none());
613    }
614
615    #[test]
616    fn exit_defaults_to_success_and_wraps_out_of_range_codes() {
617        let mut shell = test_shell();
618        let (status, _, _) = run(&mut shell, "exit");
619        assert_eq!(status, ExitStatus::SUCCESS);
620        // bash wraps modulo 256: 300 & 0xFF == 44.
621        let mut shell2 = test_shell();
622        let (status, _, _) = run(&mut shell2, "exit 300");
623        assert_eq!(status, ExitStatus::new(44));
624    }
625
626    #[test]
627    fn exit_stops_script_processing_at_the_exit_line() {
628        let mut shell = test_shell();
629        run(&mut shell, "echo 'echo before' > /tmp/exit_script.sh");
630        run(&mut shell, "echo 'exit 5' >> /tmp/exit_script.sh");
631        run(&mut shell, "echo 'echo after' >> /tmp/exit_script.sh");
632        let (status, out, _) = run(&mut shell, "bash /tmp/exit_script.sh");
633        assert_eq!(status, ExitStatus::new(5));
634        let text = String::from_utf8(out).unwrap();
635        assert!(text.contains("before"), "expected before: {text:?}");
636        assert!(!text.contains("after"), "after must not print: {text:?}");
637    }
638
639    #[test]
640    fn functions_receive_positional_parameters() {
641        let mut shell = test_shell();
642        run(&mut shell, "greet() { echo \"hello $1 ($# args)\"; }");
643        let (status, out, _) = run(&mut shell, "greet world extra");
644        assert_eq!(status, ExitStatus::SUCCESS);
645        assert_eq!(out, b"hello world (2 args)\n");
646    }
647
648    #[test]
649    fn nested_function_calls_restore_outer_parameters() {
650        let mut shell = test_shell();
651        run(&mut shell, "inner() { echo \"inner=$1\"; }");
652        run(&mut shell, "outer() { inner X; echo \"outer=$1\"; }");
653        let (_, out, _) = run(&mut shell, "outer Y");
654        let text = String::from_utf8(out).unwrap();
655        assert_eq!(text, "inner=X\nouter=Y\n");
656    }
657
658    #[test]
659    fn scripts_receive_positional_parameters() {
660        let mut shell = test_shell();
661        run(
662            &mut shell,
663            "echo 'echo \"$0 got $1 and $2\"' > /tmp/args_script.sh",
664        );
665        let (_, out, _) = run(&mut shell, "bash /tmp/args_script.sh foo bar");
666        assert_eq!(out, b"/tmp/args_script.sh got foo and bar\n");
667    }
668
669    #[test]
670    fn command_substitution_receives_positional_parameters() {
671        let mut shell = test_shell();
672        let (_, out, _) = run(&mut shell, "bash -c 'echo value=$1' prog alpha");
673        assert_eq!(out, b"value=alpha\n");
674    }
675
676    #[test]
677    fn scripts_support_pipelines_and_conditionals() {
678        let mut shell = test_shell();
679        run(
680            &mut shell,
681            "echo 'cat /etc/hostname | cat && echo ok' > /tmp/pipe_script.sh",
682        );
683        let (status, out, _) = run(&mut shell, "sh /tmp/pipe_script.sh");
684        assert_eq!(status, ExitStatus::SUCCESS);
685        let output = String::from_utf8(out).unwrap();
686        assert!(output.contains("demo-host"), "pipeline output flows");
687        assert!(output.contains("ok"), "&& runs after success");
688    }
689
690    #[test]
691    fn syntax_errors_report_usage_status() {
692        let mut shell = test_shell();
693        let (status, _, err) = run(&mut shell, "echo 'unterminated");
694        assert_eq!(status, ExitStatus::USAGE);
695        assert!(!err.is_empty());
696    }
697
698    #[test]
699    fn continuation_detects_incomplete_constructs() {
700        assert!(!needs_continuation("echo hi"));
701        assert!(needs_continuation("cat <<EOF"));
702        assert!(!needs_continuation("cat <<EOF\nbody\nEOF"));
703        assert!(needs_continuation("if true; then"));
704        assert!(!needs_continuation("if true; then echo x; fi"));
705        assert!(needs_continuation("echo 'unterminated"));
706    }
707
708    #[test]
709    fn break_stops_loops_and_continue_skips() {
710        let mut shell = test_shell();
711        run(&mut shell, "echo x > /tmp/brk_guard.txt");
712        let (status, out, _) = run(
713            &mut shell,
714            "while cat /tmp/brk_guard.txt; do echo body; rm /tmp/brk_guard.txt; break; echo never; done",
715        );
716        assert_eq!(status, ExitStatus::SUCCESS);
717        // The condition's `cat` prints the guard, then one body iteration.
718        assert_eq!(out, b"x\nbody\n", "break stops after one iteration");
719
720        let (status, out, _) = run(
721            &mut shell,
722            "for_placeholder=1; echo pre; continue; echo after",
723        );
724        let _ = status;
725        // `continue` outside a loop is a no-op: the following unit still runs.
726        assert_eq!(out, b"pre\nafter\n");
727    }
728
729    #[test]
730    fn aliases_expand_at_invocation() {
731        let mut shell = test_shell();
732        let (status, _, _) = run(&mut shell, "alias ll='echo listed'");
733        assert_eq!(status, ExitStatus::SUCCESS);
734        let (status, out, _) = run(&mut shell, "ll");
735        assert_eq!(status, ExitStatus::SUCCESS);
736        assert_eq!(out, b"listed\n");
737        // Alias with arguments appends them.
738        let (status, _, _) = run(&mut shell, "alias g='echo got'");
739        assert_eq!(status, ExitStatus::SUCCESS);
740        let (_, out, _) = run(&mut shell, "g one two");
741        assert_eq!(out, b"got one two\n");
742    }
743
744    #[test]
745    fn bash_echo_does_not_interpret_escapes_by_default() {
746        let mut shell = test_shell();
747        let (_, out, _) = run(&mut shell, "echo 'a\\tb'");
748        assert_eq!(out, b"a\\tb\n");
749        let (_, out, _) = run(&mut shell, "echo -e 'a\\tb'");
750        assert_eq!(out, b"a\tb\n");
751    }
752
753    #[test]
754    fn for_loops_iterate_and_set_the_variable() {
755        let mut shell = test_shell();
756        let (status, out, _) = run(&mut shell, "for i in 1 2 3; do echo \"i=$i\"; done");
757        assert_eq!(status, ExitStatus::SUCCESS);
758        assert_eq!(out, b"i=1\ni=2\ni=3\n");
759        let (status, out, _) = run(
760            &mut shell,
761            "for f in /etc/hostname /etc/passwd; do echo \"f=$f\"; done",
762        );
763        assert_eq!(status, ExitStatus::SUCCESS);
764        let output = String::from_utf8(out).unwrap();
765        assert!(output.contains("f=/etc/hostname"));
766        assert!(output.contains("f=/etc/passwd"));
767    }
768
769    #[test]
770    fn parameter_operators_and_substitution() {
771        let mut shell = test_shell();
772        let (_, out, _) = run(&mut shell, "echo \"${NOTSET:-fallback}\"");
773        assert_eq!(out, b"fallback\n");
774        let (_, out, _) = run(&mut shell, "echo \"${NOTSET:=set-me}\"");
775        assert_eq!(out, b"set-me\n");
776        let (_, out, _) = run(&mut shell, "echo \"$NOTSET\"");
777        assert_eq!(out, b"set-me\n");
778        run(&mut shell, "export P=/a/b/c.txt");
779        let (_, out, _) = run(&mut shell, "echo \"${P##*/}\"");
780        assert_eq!(out, b"c.txt\n");
781        let (_, out, _) = run(&mut shell, "echo \"${P%/*}\"");
782        assert_eq!(out, b"/a/b\n");
783        let (_, out, _) = run(&mut shell, "echo \"${#P}\"");
784        assert_eq!(out, b"10\n");
785        let (_, out, _) = run(&mut shell, "echo \"$(echo substituted)\"");
786        assert_eq!(out, b"substituted\n");
787        let (_, out, _) = run(&mut shell, "echo \"`echo backticked`\"");
788        assert_eq!(out, b"backticked\n");
789    }
790
791    #[test]
792    fn null_command_and_cd_dash() {
793        let mut shell = test_shell();
794        let (status, _, _) = run(&mut shell, ":");
795        assert_eq!(status, ExitStatus::SUCCESS);
796        let (_, _, _) = run(&mut shell, ": \"${BAR:=defaulted}\"");
797        let (_, out, _) = run(&mut shell, "echo \"$BAR\"");
798        assert_eq!(out, b"defaulted\n");
799        run(&mut shell, "cd /etc");
800        let (status, _, _) = run(&mut shell, "cd -");
801        assert_eq!(status, ExitStatus::SUCCESS);
802        let (_, out, _) = run(&mut shell, "pwd");
803        assert_eq!(out, b"/home/demo\n");
804    }
805
806    #[test]
807    fn stderr_redirection_works() {
808        let mut shell = test_shell();
809        let (status, _, _) = run(&mut shell, "cat /etc/nonexistent 2> /tmp/err.txt");
810        assert_eq!(status, ExitStatus::FAILURE);
811        let (_, out, _) = run(&mut shell, "cat /tmp/err.txt");
812        assert!(!out.is_empty());
813        let (_, out, _) = run(&mut shell, "cat /etc/nonexistent 2>&1");
814        assert!(!out.is_empty());
815    }
816
817    #[test]
818    fn extended_test_evaluates() {
819        let mut shell = test_shell();
820        let (status, _, _) = run(&mut shell, "[[ 1 == 1 ]]");
821        assert_eq!(status, ExitStatus::SUCCESS);
822        let (status, _, _) = run(&mut shell, "[[ -d /etc ]]");
823        assert_eq!(status, ExitStatus::SUCCESS);
824        let (status, _, _) = run(&mut shell, "[[ \"abc\" == a* ]]");
825        assert_eq!(status, ExitStatus::SUCCESS);
826        let (status, _, _) = run(&mut shell, "[[ 5 -gt 3 ]]");
827        assert_eq!(status, ExitStatus::SUCCESS);
828        let (status, _, _) = run(&mut shell, "[[ 1 == 2 ]]");
829        assert_eq!(status, ExitStatus::FAILURE);
830    }
831
832    #[test]
833    fn bash_type_reports_resolution() {
834        let mut shell = test_shell();
835        let (_, out, _) = run(&mut shell, "type cd");
836        assert_eq!(out, b"cd is a shell builtin\n");
837        let (_, out, _) = run(&mut shell, "type ls");
838        assert_eq!(out, b"ls is /usr/bin/ls\n");
839    }
840}
841
842#[cfg(test)]
843mod terminal_tests {
844    use super::*;
845    use crate::Shell;
846    use engine::{BytesInput, BytesOutput, Timestamp};
847    use os::HostIdentity;
848    use os::linux::Linux;
849    use terminal::{Size, Terminal, TerminalModel};
850
851    #[test]
852    fn terminal_is_threaded_through_compound_lines() {
853        let linux = Box::leak(Box::new(
854            Linux::with_identity(
855                &HostIdentity::new("demo", "demo-host"),
856                Timestamp::from_nanos(1_000_000),
857            )
858            .unwrap(),
859        ));
860        let credentials = linux
861            .unix()
862            .users()
863            .authenticate("demo", "demo", linux.unix().groups())
864            .unwrap();
865        let mut shell = Bash::new(linux.unix(), credentials).unwrap();
866        let mut stdin = BytesInput::new(b"");
867        let mut stdout = BytesOutput::new();
868        let mut stderr = BytesOutput::new();
869        let mut terminal = TerminalModel::new(Size::new(24, 80));
870        terminal.push_keys(&[terminal::KeyEvent::character('q')]);
871        // man consumes the terminal; the following unit still runs and the
872        // terminal remains usable (main screen restored).
873        let status = shell.execute_with_terminal(
874            "man ls; echo done",
875            &mut stdin,
876            &mut stdout,
877            &mut stderr,
878            Some(&mut terminal),
879        );
880        assert_eq!(status, ExitStatus::SUCCESS);
881        assert_eq!(stdout.into_bytes(), b"done\n");
882        assert!(!terminal.in_alternate_screen());
883    }
884}