| 1 | #!/bin/sh |
| 2 | TEST_PREFIX="[local]" |
| 3 | . "$(cd "$(dirname "$0")/.." && pwd)/test_harness.sh" |
| 4 | |
| 5 | section "1. local scope" |
| 6 | compare_output "local restricts scope to function" 'f() { local x=inner; echo $x; }; f; echo ">${x}<"' |
| 7 | compare_output "local with initial value" 'f() { local msg=hello; echo $msg; }; f' |
| 8 | compare_output "local does not leak outside" 'f() { local secret=42; }; f; echo ">${secret}<"' |
| 9 | compare_output "local shadows outer variable" 'x=outer; f() { local x=inner; echo $x; }; f; echo $x' |
| 10 | compare_exit "local outside function fails" 'local x=5 2>/dev/null' |
| 11 | |
| 12 | section "2. local advanced" |
| 13 | compare_output "local without value" 'f() { local x; echo ">${x}<"; }; f' |
| 14 | compare_output "local multiple vars" 'f() { local a=1 b=2; echo $a $b; }; f' |
| 15 | compare_output "local preserves outer after return" 'x=outer; f() { local x=inner; return; }; f; echo $x' |
| 16 | compare_output "nested function locals" 'g() { local x=inner2; echo $x; }; f() { local x=inner1; g; echo $x; }; f' |
| 17 | compare_output "local in nested calls" 'x=global; f() { local x=f_val; g; echo $x; }; g() { echo $x; }; f; echo $x' |
| 18 | |
| 19 | section "3. local with types" |
| 20 | compare_output "local -i integer" 'f() { local -i n=5+3; echo $n; }; f' |
| 21 | compare_output "local -a array" 'f() { local -a arr=(a b c); echo ${arr[@]}; }; f' |
| 22 | compare_output "local -r readonly" 'f() { local -r x=fixed; echo $x; }; f' |
| 23 | |
| 24 | print_summary |