Skip to content

Commit b2e6d88

Browse files
authored
fix(interpreter): expand special variables ($#, $?, etc.) in arithmetic (#887)
## Summary - Special variables like `$#`, `$?`, `$$` were not expanded inside `(( ))` arithmetic because `expand_arithmetic_vars_depth` only consumed alphanumeric/underscore chars after `$` - Add handling for special variable characters (`#`, `?`, `$`, `!`, `@`, `*`, `-`) in the arithmetic variable expansion - Add spec tests `arith_special_var_hash` and `arith_special_var_question` ## Test plan - [x] New spec tests pass - [x] All 1812 bash spec tests pass (100%) - [x] Full `cargo test --all-features` passes - [x] `cargo fmt --check` and `cargo clippy` clean Closes #876
1 parent 059eb85 commit b2e6d88

2 files changed

Lines changed: 34 additions & 0 deletions

File tree

crates/bashkit/src/interpreter/mod.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7169,6 +7169,17 @@ impl Interpreter {
71697169
} else {
71707170
result.push_str(&expanded);
71717171
}
7172+
} else if let Some(&c) = chars.peek()
7173+
&& matches!(c, '#' | '?' | '$' | '!' | '@' | '*' | '-')
7174+
{
7175+
// Handle special variables: $#, $?, $$, $!, $@, $*, $-
7176+
chars.next();
7177+
let value = self.expand_variable(&c.to_string());
7178+
if value.is_empty() {
7179+
result.push('0');
7180+
} else {
7181+
result.push_str(&value);
7182+
}
71727183
} else {
71737184
// Handle $var syntax (common in arithmetic)
71747185
let mut name = String::new();

crates/bashkit/tests/spec_cases/bash/arithmetic.test.sh

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -493,3 +493,26 @@ echo $x
493493
### expect
494494
42
495495
### end
496+
497+
### arith_special_var_hash
498+
# $# in arithmetic context
499+
set -- a b c
500+
echo "argc: $#"
501+
(( $# > 0 )) && echo "true" || echo "false"
502+
(( 3 > 0 )) && echo "true2" || echo "false2"
503+
x=$#
504+
(( x > 0 )) && echo "true3" || echo "false3"
505+
### expect
506+
argc: 3
507+
true
508+
true2
509+
true3
510+
### end
511+
512+
### arith_special_var_question
513+
# $? in arithmetic context
514+
true
515+
(( $? == 0 )) && echo "zero" || echo "nonzero"
516+
### expect
517+
zero
518+
### end

0 commit comments

Comments
 (0)