use engine::{Input, Output, Terminal, VirtualPath};
use os::{Credentials, ExitStatus, UnixOs};
use crate::core::{ShellCore, ShellDialect};
pub struct Bash<'os> {
core: ShellCore<'os>,
}
impl<'os> Bash<'os> {
pub fn new(os: &'os UnixOs, credentials: Credentials) -> Result<Self, os::OsError> {
let mut core = ShellCore::new(os, credentials, bash_dialect())?;
core.install_shell_bindings();
core.source_startup_files();
Ok(Self { core })
}
}
pub struct BashInterpreter;
impl os::runtime::Command for BashInterpreter {
fn name(&self) -> &'static str {
"bash"
}
fn execute(
&self,
context: &mut os::runtime::CommandContext<'_, '_, '_, '_>,
) -> Result<os::runtime::ExitStatus, os::OsError> {
crate::core::run_interpreter_invocation(
context.os,
context.credentials.clone(),
bash_dialect(),
context.cwd,
context.argv,
&mut *context.stdin,
&mut *context.stdout,
&mut *context.stderr,
)
}
}
pub(crate) fn bash_dialect() -> ShellDialect {
ShellDialect {
name: "bash",
command_not_found: |name| format!("bash: {name}: command not found\n"),
run_builtin: bash_run_builtin,
system_rc: "/etc/bashrc",
user_rc: ".bashrc",
echo_escapes_default: false,
export_prefix: "declare -x ",
alias_prefix: "alias ",
}
}
fn bash_is_builtin(name: &str) -> bool {
matches!(
name,
"cd" | "pwd"
| "export"
| "history"
| "alias"
| "unalias"
| "jobs"
| "fg"
| "bg"
| "wait"
| "hash"
| "echo"
| "clear"
| ":"
| "dirs"
| "pushd"
| "popd"
| "unset"
| "source"
| "."
| "type"
| "exit"
)
}
fn bash_run_builtin(
core: &mut ShellCore,
name: &str,
argv: &[String],
stdin: &mut dyn Input,
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> Option<ExitStatus> {
let status = match name {
"cd" => core.cd_to(argv, stdout, stderr),
"pwd" => core.pwd_of(stdout),
"jobs" => core.list_jobs(stdout),
"fg" => core.foreground_job(argv, stdout, stderr),
"bg" => core.background_job(argv, stdout, stderr),
"wait" => core.wait_for_jobs(argv, stderr),
"hash" => core.hash_table(argv, stdout, stderr),
"dirs" => core.print_dirs(stdout),
"pushd" => core.push_directory(argv, stdout, stderr),
"popd" => core.pop_directory(argv, stdout, stderr),
"unset" => core.unset_names(argv, stderr),
"source" | "." => core.source_file(argv, stdin, stdout, stderr),
"clear" => core.clear_screen(stdout),
":" => core.null_command(),
"echo" => core.builtin_echo(argv, stdout),
"export" => core.builtin_export(argv, stdout, stderr),
"history" => core.builtin_history(stdout),
"alias" => core.builtin_alias(argv, stdout, stderr),
"unalias" => core.builtin_unalias(argv, stderr),
"type" => bash_type(core, argv, stdout, stderr),
"exit" => core.request_exit(argv.get(1).map(String::as_str)),
_ => return None,
};
Some(status)
}
fn bash_type(
core: &mut ShellCore,
argv: &[String],
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> ExitStatus {
let mut exit_status = ExitStatus::SUCCESS;
for name in argv.iter().skip(1) {
let resolution = core.resolve_name(name, bash_is_builtin);
if let Some(alias) = resolution.alias {
let _ = stdout.write(format!("{name} is aliased to `{alias}'\n").as_bytes());
continue;
}
if resolution.function {
let _ = stdout.write(format!("{name} is a function\n").as_bytes());
continue;
}
if resolution.builtin {
let _ = stdout.write(format!("{name} is a shell builtin\n").as_bytes());
continue;
}
if let Some(path) = resolution.paths.into_iter().next() {
let _ = stdout.write(format!("{name} is {path}\n").as_bytes());
} else {
exit_status = ExitStatus::FAILURE;
let _ = stderr.write(format!("bash: type: {name}: not found\n").as_bytes());
}
}
exit_status
}
impl<'os> crate::Shell for Bash<'os> {
fn name(&self) -> &'static str {
"bash"
}
fn actor(&self) -> engine::ActorId {
self.core.credentials().actor()
}
fn environment(&self) -> &os::Environment {
self.core.environment()
}
fn engine(&self) -> &engine::Engine {
self.core.os().engine()
}
fn boot_time(&self) -> engine::Timestamp {
self.core.os().boot_time()
}
fn hostname(&self) -> String {
crate::core::hostname_from_etc(self.core.os())
}
fn cwd(&self) -> &VirtualPath {
self.core.cwd()
}
fn prompt(&self, hostname: &str) -> String {
format!(
"{}@{}:{}> ",
self.core.credentials().username(),
hostname,
self.core.cwd()
)
}
fn banner(&self) -> Option<String> {
Some(format!(
"Last login: {} on ttys000\n",
crate::core::format_login_line(self.core.os().boot_time())
))
}
fn set_terminal_size(&mut self, rows: u16, cols: u16) {
self.core.set_terminal_size(rows, cols);
}
fn execute(
&mut self,
line: &str,
stdin: &mut dyn Input,
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> ExitStatus {
self.core.execute(line, stdin, stdout, stderr)
}
fn execute_with_terminal(
&mut self,
line: &str,
stdin: &mut dyn Input,
stdout: &mut dyn Output,
stderr: &mut dyn Output,
terminal: Option<&mut dyn Terminal>,
) -> ExitStatus {
self.core
.execute_with_terminal(line, stdin, stdout, stderr, terminal)
}
fn take_exit_status(&mut self) -> Option<ExitStatus> {
self.core.take_exit_request()
}
fn history(&self) -> &[String] {
self.core.history()
}
fn record_history(&mut self, line: &str) {
self.core.record_history(line);
}
fn needs_continuation(&self, input: &str) -> bool {
crate::core::needs_continuation(input)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Shell;
use crate::core::needs_continuation;
use engine::{BytesInput, BytesOutput, Timestamp};
use os::HostIdentity;
use os::linux::Linux;
fn test_shell() -> Bash<'static> {
let linux = Box::leak(Box::new(
Linux::with_identity(
&HostIdentity::new("demo", "demo-host"),
Timestamp::from_nanos(1_000_000),
)
.unwrap(),
));
let credentials = linux
.unix()
.users()
.authenticate("demo", "demo", linux.unix().groups())
.unwrap();
Bash::new(linux.unix(), credentials).unwrap()
}
fn run(shell: &mut Bash<'static>, line: &str) -> (ExitStatus, Vec<u8>, Vec<u8>) {
let mut stdin = BytesInput::new(b"");
let mut stdout = BytesOutput::new();
let mut stderr = BytesOutput::new();
let status = shell.execute(line, &mut stdin, &mut stdout, &mut stderr);
(status, stdout.into_bytes(), stderr.into_bytes())
}
#[test]
fn builtin_cd_and_pwd() {
let mut shell = test_shell();
assert_eq!(run(&mut shell, "mkdir /tmp/testdir").0, ExitStatus::SUCCESS);
let (status, _, _) = run(&mut shell, "cd /tmp/testdir");
assert_eq!(status, ExitStatus::SUCCESS);
assert_eq!(shell.cwd().to_string(), "/tmp/testdir");
let (_, out, _) = run(&mut shell, "pwd");
assert_eq!(out, b"/tmp/testdir\n");
}
#[test]
fn external_ls_and_which() {
let mut shell = test_shell();
let (status, out, _) = run(&mut shell, "which ls");
assert_eq!(status, ExitStatus::SUCCESS);
assert_eq!(out, b"/usr/bin/ls\n");
let (status, out, _) = run(&mut shell, "ls /");
assert_eq!(status, ExitStatus::SUCCESS);
let output = String::from_utf8(out).unwrap();
assert!(output.contains("bin"));
assert!(output.contains("etc"));
}
#[test]
fn redirection_and_cat() {
let mut shell = test_shell();
let (status, out, _) = run(&mut shell, "echo hello > /tmp/hello.txt");
assert_eq!(status, ExitStatus::SUCCESS);
assert_eq!(out, b"");
let (status, out, _) = run(&mut shell, "cat /tmp/hello.txt");
assert_eq!(status, ExitStatus::SUCCESS);
assert_eq!(out, b"hello\n");
}
#[test]
fn single_quotes_do_not_expand() {
let mut shell = test_shell();
let (_, out, _) = run(&mut shell, "echo '$HOME'");
assert_eq!(out, b"$HOME\n");
}
#[test]
fn double_quotes_expand_but_do_not_split() {
let mut shell = test_shell();
let (_, out, _) = run(&mut shell, "echo \"$HOME/x y\"");
assert_eq!(out, b"/home/demo/x y\n");
}
#[test]
fn quoted_operators_are_not_operators() {
let mut shell = test_shell();
let (status, out, _) = run(&mut shell, "echo \"a & b; c\"");
assert_eq!(status, ExitStatus::SUCCESS);
assert_eq!(out, b"a & b; c\n");
}
#[test]
fn and_or_sequencing_preserves_quoting() {
let mut shell = test_shell();
let (status, out, _) = run(
&mut shell,
"echo 'first word' > /tmp/q.txt && cat /tmp/q.txt",
);
assert_eq!(status, ExitStatus::SUCCESS);
assert_eq!(out, b"first word\n");
}
#[test]
fn background_ampersand_is_recorded() {
let mut shell = test_shell();
let (_, out, _) = run(&mut shell, "echo backgrounded & echo foreground");
assert_eq!(out, b"backgrounded\nforeground\n");
let (_, jobs, _) = run(&mut shell, "jobs");
assert!(String::from_utf8_lossy(&jobs).contains("echo backgrounded"));
}
#[test]
fn arithmetic_expansion_evaluates() {
let mut shell = test_shell();
let (_, out, _) = run(&mut shell, "echo $((1 + 1))");
assert_eq!(out, b"2\n");
let (_, out, _) = run(&mut shell, "echo $((2 + 3 * 4))");
assert_eq!(out, b"14\n");
let (_, out, _) = run(&mut shell, "echo $(((2 + 3) * 4))");
assert_eq!(out, b"20\n");
run(&mut shell, "count=5");
let (_, out, _) = run(&mut shell, "echo $((count * 2))");
assert_eq!(out, b"10\n");
run(&mut shell, "((count += 3))");
let (_, out, _) = run(&mut shell, "echo $count");
assert_eq!(out, b"8\n");
let (_, out, _) = run(&mut shell, "echo $(($(grep -c . /dev/null) + 7))");
assert_eq!(out, b"7\n");
}
#[test]
fn arithmetic_command_reports_nonzero_as_success() {
let mut shell = test_shell();
let (status, _, _) = run(&mut shell, "((1 + 1))");
assert_eq!(status, ExitStatus::SUCCESS);
let (status, _, _) = run(&mut shell, "((1 - 1))");
assert_eq!(status.code(), 1);
}
#[test]
fn case_clause_matches_patterns_in_order() {
let mut shell = test_shell();
let (_, out, _) = run(
&mut shell,
"case /etc/passwd in /etc/*) echo system ;; *) echo other ;; esac",
);
assert_eq!(out, b"system\n");
let (status, out, _) = run(&mut shell, "case zzz in aaa) echo a ;; esac");
assert_eq!(status, ExitStatus::SUCCESS);
assert_eq!(out, b"");
let (_, out, _) = run(
&mut shell,
"case abc in a*) echo one ;; *) echo two ;; esac",
);
assert_eq!(out, b"one\n");
}
#[test]
fn subshell_isolates_state() {
let mut shell = test_shell();
run(&mut shell, "cd /tmp && mkdir -p /tmp/subshell-test");
let (status, out, _) = run(
&mut shell,
"(value=inner; cd /tmp/subshell-test); echo $value; pwd",
);
assert_eq!(status, ExitStatus::SUCCESS);
assert_eq!(out, b"\n/tmp\n");
let (status, out, _) = run(&mut shell, "(false || echo recovered)");
assert_eq!(status, ExitStatus::SUCCESS);
assert_eq!(out, b"recovered\n");
}
#[test]
fn bang_negates_pipeline_status() {
let mut shell = test_shell();
run(&mut shell, "echo x > /tmp/real_file.txt");
let (status, _, _) = run(&mut shell, "! cat /tmp/real_file.txt");
assert_eq!(status, ExitStatus::FAILURE, "! <success> fails");
let (status, _, _) = run(&mut shell, "! cat /tmp/none");
assert_eq!(status, ExitStatus::SUCCESS, "! <failure> succeeds");
}
#[test]
fn if_elif_else_executes() {
let mut shell = test_shell();
run(&mut shell, "echo yes > /tmp/marker.txt");
let (status, out, _) = run(
&mut shell,
"if cat /tmp/marker.txt; then echo branch-then; elif cat /tmp/none; then echo branch-elif; else echo branch-else; fi",
);
assert_eq!(status, ExitStatus::SUCCESS);
assert_eq!(out, b"yes\nbranch-then\n");
let (status, out, _) = run(
&mut shell,
"if cat /tmp/none; then echo branch-then; elif cat /tmp/marker.txt; then echo branch-elif; else echo branch-else; fi",
);
assert_eq!(status, ExitStatus::SUCCESS);
assert_eq!(out, b"yes\nbranch-elif\n");
let (status, out, _) = run(
&mut shell,
"if cat /tmp/none; then echo branch-then; else echo branch-else; fi",
);
assert_eq!(status, ExitStatus::SUCCESS);
assert_eq!(out, b"branch-else\n");
}
#[test]
fn while_loops_until_the_condition_fails() {
let mut shell = test_shell();
run(&mut shell, "echo guard > /tmp/loop_guard.txt");
let (status, _, _) = run(
&mut shell,
"while cat /tmp/loop_guard.txt; do rm /tmp/loop_guard.txt; done",
);
assert_eq!(status, ExitStatus::SUCCESS);
let (status, _, _) = run(&mut shell, "cat /tmp/loop_guard.txt");
assert_eq!(
status,
ExitStatus::FAILURE,
"the loop body removed the guard"
);
}
#[test]
fn functions_are_defined_and_called() {
let mut shell = test_shell();
let (status, _, _) = run(&mut shell, "greet() { echo hello; }");
assert_eq!(status, ExitStatus::SUCCESS);
let (status, out, _) = run(&mut shell, "greet");
assert_eq!(status, ExitStatus::SUCCESS);
assert_eq!(out, b"hello\n");
}
#[test]
fn assignments_prefix_the_command_environment() {
let mut shell = test_shell();
let (status, out, _) = run(&mut shell, "PATH=/bin which ls");
assert_eq!(status, ExitStatus::SUCCESS);
assert_eq!(out, b"/bin/ls\n");
}
#[test]
fn bare_assignments_persist_in_the_shell() {
let mut shell = test_shell();
let (status, _, _) = run(&mut shell, "MYVAR=hello");
assert_eq!(status, ExitStatus::SUCCESS);
assert_eq!(shell.environment().get("MYVAR"), Some("hello"));
let (_, out, _) = run(&mut shell, "echo $MYVAR");
assert_eq!(out, b"hello\n");
}
#[test]
fn heredoc_feeds_stdin() {
let mut shell = test_shell();
let (status, out, _) = run(&mut shell, "cat <<EOF\nhello heredoc\nEOF");
assert_eq!(status, ExitStatus::SUCCESS);
assert_eq!(out, b"hello heredoc\n");
}
#[test]
fn pipeline_pipes_output() {
let mut shell = test_shell();
run(&mut shell, "echo hello > /tmp/a.txt");
let (status, out, _) = run(&mut shell, "cat /tmp/a.txt | cat");
assert_eq!(status, ExitStatus::SUCCESS);
assert_eq!(out, b"hello\n");
}
#[test]
fn globs_expand_unquoted_stars() {
let mut shell = test_shell();
run(&mut shell, "echo a > /tmp/glob_a.txt");
run(&mut shell, "echo b > /tmp/glob_b.txt");
let (status, out, _) = run(&mut shell, "echo /tmp/glob_*.txt");
assert_eq!(status, ExitStatus::SUCCESS);
let output = String::from_utf8(out).unwrap();
assert!(output.contains("glob_a.txt"));
assert!(output.contains("glob_b.txt"));
let (_, out, _) = run(&mut shell, "echo '/tmp/glob_*.txt'");
assert_eq!(out, b"/tmp/glob_*.txt\n");
}
#[test]
fn mv_overwrites_existing_files() {
let mut shell = test_shell();
run(&mut shell, "echo one > /tmp/a.txt");
run(&mut shell, "echo two > /tmp/b.txt");
let (status, _, _) = run(&mut shell, "mv /tmp/a.txt /tmp/b.txt");
assert_eq!(status, ExitStatus::SUCCESS);
let (_, out, _) = run(&mut shell, "cat /tmp/b.txt");
assert_eq!(out, b"one\n");
let (status, _, _) = run(&mut shell, "cat /tmp/a.txt");
assert_eq!(status, ExitStatus::FAILURE);
}
#[test]
fn scripts_run_through_the_interpreter() {
let mut shell = test_shell();
run(
&mut shell,
"echo 'echo hello > /tmp/script_out.txt' > /tmp/script.sh",
);
let (status, _, _) = run(&mut shell, "sh /tmp/script.sh");
assert_eq!(status, ExitStatus::SUCCESS);
let (_, out, _) = run(&mut shell, "cat /tmp/script_out.txt");
assert_eq!(out, b"hello\n");
}
#[test]
fn exit_carries_a_status_and_requests_session_end() {
let mut shell = test_shell();
assert!(shell.take_exit_status().is_none());
let (status, _, _) = run(&mut shell, "exit 7");
assert_eq!(status, ExitStatus::new(7));
assert_eq!(shell.take_exit_status(), Some(ExitStatus::new(7)));
assert!(shell.take_exit_status().is_none());
}
#[test]
fn exit_defaults_to_success_and_wraps_out_of_range_codes() {
let mut shell = test_shell();
let (status, _, _) = run(&mut shell, "exit");
assert_eq!(status, ExitStatus::SUCCESS);
let mut shell2 = test_shell();
let (status, _, _) = run(&mut shell2, "exit 300");
assert_eq!(status, ExitStatus::new(44));
}
#[test]
fn exit_stops_script_processing_at_the_exit_line() {
let mut shell = test_shell();
run(&mut shell, "echo 'echo before' > /tmp/exit_script.sh");
run(&mut shell, "echo 'exit 5' >> /tmp/exit_script.sh");
run(&mut shell, "echo 'echo after' >> /tmp/exit_script.sh");
let (status, out, _) = run(&mut shell, "bash /tmp/exit_script.sh");
assert_eq!(status, ExitStatus::new(5));
let text = String::from_utf8(out).unwrap();
assert!(text.contains("before"), "expected before: {text:?}");
assert!(!text.contains("after"), "after must not print: {text:?}");
}
#[test]
fn functions_receive_positional_parameters() {
let mut shell = test_shell();
run(&mut shell, "greet() { echo \"hello $1 ($# args)\"; }");
let (status, out, _) = run(&mut shell, "greet world extra");
assert_eq!(status, ExitStatus::SUCCESS);
assert_eq!(out, b"hello world (2 args)\n");
}
#[test]
fn nested_function_calls_restore_outer_parameters() {
let mut shell = test_shell();
run(&mut shell, "inner() { echo \"inner=$1\"; }");
run(&mut shell, "outer() { inner X; echo \"outer=$1\"; }");
let (_, out, _) = run(&mut shell, "outer Y");
let text = String::from_utf8(out).unwrap();
assert_eq!(text, "inner=X\nouter=Y\n");
}
#[test]
fn scripts_receive_positional_parameters() {
let mut shell = test_shell();
run(
&mut shell,
"echo 'echo \"$0 got $1 and $2\"' > /tmp/args_script.sh",
);
let (_, out, _) = run(&mut shell, "bash /tmp/args_script.sh foo bar");
assert_eq!(out, b"/tmp/args_script.sh got foo and bar\n");
}
#[test]
fn command_substitution_receives_positional_parameters() {
let mut shell = test_shell();
let (_, out, _) = run(&mut shell, "bash -c 'echo value=$1' prog alpha");
assert_eq!(out, b"value=alpha\n");
}
#[test]
fn scripts_support_pipelines_and_conditionals() {
let mut shell = test_shell();
run(
&mut shell,
"echo 'cat /etc/hostname | cat && echo ok' > /tmp/pipe_script.sh",
);
let (status, out, _) = run(&mut shell, "sh /tmp/pipe_script.sh");
assert_eq!(status, ExitStatus::SUCCESS);
let output = String::from_utf8(out).unwrap();
assert!(output.contains("demo-host"), "pipeline output flows");
assert!(output.contains("ok"), "&& runs after success");
}
#[test]
fn syntax_errors_report_usage_status() {
let mut shell = test_shell();
let (status, _, err) = run(&mut shell, "echo 'unterminated");
assert_eq!(status, ExitStatus::USAGE);
assert!(!err.is_empty());
}
#[test]
fn continuation_detects_incomplete_constructs() {
assert!(!needs_continuation("echo hi"));
assert!(needs_continuation("cat <<EOF"));
assert!(!needs_continuation("cat <<EOF\nbody\nEOF"));
assert!(needs_continuation("if true; then"));
assert!(!needs_continuation("if true; then echo x; fi"));
assert!(needs_continuation("echo 'unterminated"));
}
#[test]
fn break_stops_loops_and_continue_skips() {
let mut shell = test_shell();
run(&mut shell, "echo x > /tmp/brk_guard.txt");
let (status, out, _) = run(
&mut shell,
"while cat /tmp/brk_guard.txt; do echo body; rm /tmp/brk_guard.txt; break; echo never; done",
);
assert_eq!(status, ExitStatus::SUCCESS);
assert_eq!(out, b"x\nbody\n", "break stops after one iteration");
let (status, out, _) = run(
&mut shell,
"for_placeholder=1; echo pre; continue; echo after",
);
let _ = status;
assert_eq!(out, b"pre\nafter\n");
}
#[test]
fn aliases_expand_at_invocation() {
let mut shell = test_shell();
let (status, _, _) = run(&mut shell, "alias ll='echo listed'");
assert_eq!(status, ExitStatus::SUCCESS);
let (status, out, _) = run(&mut shell, "ll");
assert_eq!(status, ExitStatus::SUCCESS);
assert_eq!(out, b"listed\n");
let (status, _, _) = run(&mut shell, "alias g='echo got'");
assert_eq!(status, ExitStatus::SUCCESS);
let (_, out, _) = run(&mut shell, "g one two");
assert_eq!(out, b"got one two\n");
}
#[test]
fn bash_echo_does_not_interpret_escapes_by_default() {
let mut shell = test_shell();
let (_, out, _) = run(&mut shell, "echo 'a\\tb'");
assert_eq!(out, b"a\\tb\n");
let (_, out, _) = run(&mut shell, "echo -e 'a\\tb'");
assert_eq!(out, b"a\tb\n");
}
#[test]
fn for_loops_iterate_and_set_the_variable() {
let mut shell = test_shell();
let (status, out, _) = run(&mut shell, "for i in 1 2 3; do echo \"i=$i\"; done");
assert_eq!(status, ExitStatus::SUCCESS);
assert_eq!(out, b"i=1\ni=2\ni=3\n");
let (status, out, _) = run(
&mut shell,
"for f in /etc/hostname /etc/passwd; do echo \"f=$f\"; done",
);
assert_eq!(status, ExitStatus::SUCCESS);
let output = String::from_utf8(out).unwrap();
assert!(output.contains("f=/etc/hostname"));
assert!(output.contains("f=/etc/passwd"));
}
#[test]
fn parameter_operators_and_substitution() {
let mut shell = test_shell();
let (_, out, _) = run(&mut shell, "echo \"${NOTSET:-fallback}\"");
assert_eq!(out, b"fallback\n");
let (_, out, _) = run(&mut shell, "echo \"${NOTSET:=set-me}\"");
assert_eq!(out, b"set-me\n");
let (_, out, _) = run(&mut shell, "echo \"$NOTSET\"");
assert_eq!(out, b"set-me\n");
run(&mut shell, "export P=/a/b/c.txt");
let (_, out, _) = run(&mut shell, "echo \"${P##*/}\"");
assert_eq!(out, b"c.txt\n");
let (_, out, _) = run(&mut shell, "echo \"${P%/*}\"");
assert_eq!(out, b"/a/b\n");
let (_, out, _) = run(&mut shell, "echo \"${#P}\"");
assert_eq!(out, b"10\n");
let (_, out, _) = run(&mut shell, "echo \"$(echo substituted)\"");
assert_eq!(out, b"substituted\n");
let (_, out, _) = run(&mut shell, "echo \"`echo backticked`\"");
assert_eq!(out, b"backticked\n");
}
#[test]
fn null_command_and_cd_dash() {
let mut shell = test_shell();
let (status, _, _) = run(&mut shell, ":");
assert_eq!(status, ExitStatus::SUCCESS);
let (_, _, _) = run(&mut shell, ": \"${BAR:=defaulted}\"");
let (_, out, _) = run(&mut shell, "echo \"$BAR\"");
assert_eq!(out, b"defaulted\n");
run(&mut shell, "cd /etc");
let (status, _, _) = run(&mut shell, "cd -");
assert_eq!(status, ExitStatus::SUCCESS);
let (_, out, _) = run(&mut shell, "pwd");
assert_eq!(out, b"/home/demo\n");
}
#[test]
fn stderr_redirection_works() {
let mut shell = test_shell();
let (status, _, _) = run(&mut shell, "cat /etc/nonexistent 2> /tmp/err.txt");
assert_eq!(status, ExitStatus::FAILURE);
let (_, out, _) = run(&mut shell, "cat /tmp/err.txt");
assert!(!out.is_empty());
let (_, out, _) = run(&mut shell, "cat /etc/nonexistent 2>&1");
assert!(!out.is_empty());
}
#[test]
fn extended_test_evaluates() {
let mut shell = test_shell();
let (status, _, _) = run(&mut shell, "[[ 1 == 1 ]]");
assert_eq!(status, ExitStatus::SUCCESS);
let (status, _, _) = run(&mut shell, "[[ -d /etc ]]");
assert_eq!(status, ExitStatus::SUCCESS);
let (status, _, _) = run(&mut shell, "[[ \"abc\" == a* ]]");
assert_eq!(status, ExitStatus::SUCCESS);
let (status, _, _) = run(&mut shell, "[[ 5 -gt 3 ]]");
assert_eq!(status, ExitStatus::SUCCESS);
let (status, _, _) = run(&mut shell, "[[ 1 == 2 ]]");
assert_eq!(status, ExitStatus::FAILURE);
}
#[test]
fn bash_type_reports_resolution() {
let mut shell = test_shell();
let (_, out, _) = run(&mut shell, "type cd");
assert_eq!(out, b"cd is a shell builtin\n");
let (_, out, _) = run(&mut shell, "type ls");
assert_eq!(out, b"ls is /usr/bin/ls\n");
}
}
#[cfg(test)]
mod terminal_tests {
use super::*;
use crate::Shell;
use engine::{BytesInput, BytesOutput, Timestamp};
use os::HostIdentity;
use os::linux::Linux;
use terminal::{Size, Terminal, TerminalModel};
#[test]
fn terminal_is_threaded_through_compound_lines() {
let linux = Box::leak(Box::new(
Linux::with_identity(
&HostIdentity::new("demo", "demo-host"),
Timestamp::from_nanos(1_000_000),
)
.unwrap(),
));
let credentials = linux
.unix()
.users()
.authenticate("demo", "demo", linux.unix().groups())
.unwrap();
let mut shell = Bash::new(linux.unix(), credentials).unwrap();
let mut stdin = BytesInput::new(b"");
let mut stdout = BytesOutput::new();
let mut stderr = BytesOutput::new();
let mut terminal = TerminalModel::new(Size::new(24, 80));
terminal.push_keys(&[terminal::KeyEvent::character('q')]);
let status = shell.execute_with_terminal(
"man ls; echo done",
&mut stdin,
&mut stdout,
&mut stderr,
Some(&mut terminal),
);
assert_eq!(status, ExitStatus::SUCCESS);
assert_eq!(stdout.into_bytes(), b"done\n");
assert!(!terminal.in_alternate_screen());
}
}