Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions crates/bashkit/src/interpreter/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5914,9 +5914,15 @@ impl Interpreter {
"maximum nesting depth exceeded in command substitution".to_string(),
));
}
// Command substitution runs in a subshell: snapshot trap state
// so EXIT traps set inside $() fire and don't leak to parent.
// Command substitution runs in a subshell: snapshot all
// mutable state so mutations don't leak to the parent.
let saved_traps = self.traps.clone();
let saved_functions = self.functions.clone();
let saved_vars = self.variables.clone();
let saved_arrays = self.arrays.clone();
let saved_assoc = self.assoc_arrays.clone();
let saved_aliases = self.aliases.clone();
let saved_cwd = self.cwd.clone();
let mut stdout = String::new();
for cmd in commands {
let cmd_result = self.execute_command(cmd).await?;
Expand All @@ -5940,8 +5946,14 @@ impl Interpreter {
{
stdout.push_str(&trap_result.stdout);
}
// Restore parent trap state
// Restore parent state
self.traps = saved_traps;
self.functions = saved_functions;
self.variables = saved_vars;
self.arrays = saved_arrays;
self.assoc_arrays = saved_assoc;
self.aliases = saved_aliases;
self.cwd = saved_cwd;
self.counters.pop_function();
self.subst_generation += 1;
let trimmed = stdout.trim_end_matches('\n');
Expand Down
30 changes: 30 additions & 0 deletions crates/bashkit/tests/spec_cases/bash/command-subst.test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -223,3 +223,33 @@ trap - EXIT
result=[inner
CHILD]
### end

### subst_function_isolation
# Functions defined in $() should not leak to parent shell
x=$(function foo() { echo "sub"; }; echo "ok")
echo "$x"
foo 2>/dev/null
echo "exit=$?"
### expect
ok
exit=127
### end

### subst_variable_isolation
# Variables set in $() should not leak to parent shell
myvar="before"
x=$(myvar="inside"; echo "ok")
echo "$x"
echo "$myvar"
### expect
ok
before
### end

### subst_alias_isolation
# Aliases set in $() should not leak to parent shell
x=$(alias myalias='echo aliased' 2>/dev/null; echo "ok")
echo "$x"
### expect
ok
### end
Loading