Posted by 4Aiur on 03/10/2012 in
Shell |
∞
Variable scope in subshell
functions
[mlf4aiur@4aiur Shell]$ cat function_return.sh
subshell () {
# pipeline will generate subshell
echo 1 2 3 | while read line
do
echo "subshell: inside 1"; var=1; return 1
done
echo "subshell: inside 0"; var=0; return 0
}
subshell
echo "subshell: outside return $? var=$var"
foo () {
for line in $(echo 1 2 3)
do
echo "foo: inside 1"; var=1; return 1
done
echo "foo: inside 0"; var=0; return 0
}
foo
echo "foo: outside return $? var=$var"
bar () {
while read line
do
echo "bar: inside 1"; var=1; return 1
# Bash Process Substitution, original shell doesn't work
done
using shell run it
[mlf4aiur@4aiur Shell]$ sh function_return.sh
subshell: inside 1
subshell: inside 0
subshell: outside return 0 var=0
foo: inside 1
foo: outside return 1 var=1
function_return.sh: line 28: syntax error near unexpected token `
using bash run it
[mlf4aiur@4aiur Shell]$ bash function_return.sh
subshell: inside 1
subshell: inside 0
subshell: outside return 0 var=0
foo: inside 1
foo: outside return 1 var=1
bar: inside 1
bar: outside return 1 var=1
[mlf4aiur@4aiur Shell]$
Tags: subshell