the following script mimics a problem I met in a larger script.
loop-break-example-functions.sh :
#!/bin/ksh
#!/bin/bash
function loop_function {
echo_function | while read one two three
do
echo $one $two $three
echo "in loop 1 onefound = $onefound"
if [[ $two == "BB" ]]
then
onefound=$one
echo "in loop in if onefound = $onefound"
break
fi
echo "in loop 2 onefound = $onefound"
done
echo "end onefound = $onefound"
}
function echo_function {
while read line
do
echo $line
done <<EEE
A B C
AA BB CC
AAA BBB CCC
EEE
}
loop_function
I works well in ksh but not in bash. When the shell is bash, the value of variable $onefound is lost in the end.
With ksh
# ./loop-break-example-functions.sh
A B C
in loop 1 onefound =
in loop 2 onefound =
AA BB CC
in loop 1 onefound =
in loop in if onefound = AA
end onefound = AA
#
switching the 2 first lines to work with bash :
# ./loop-break-example-functions.sh
A B C
in loop 1 onefound =
in loop 2 onefound =
AA BB CC
in loop 1 onefound =
in loop in if onefound = AA
end onefound =
#
Can somebody explain the difference ? How can I make it work in bash ?
I tried giving onefound an initial value in the beginning of the function.
I saw that there is no problem when the input is more straighforward (not coming from a function). The following version is OK with both shells :
#!/bin/ksh
#!/bin/bash
function loop_function {
while read one two three
do
echo $one $two $three
echo "in loop 1 onefound = $onefound"
if [[ $two == "BB" ]]
then
onefound=$one
echo "in loop in if onefound = $onefound"
break
fi
echo "in loop 2 onefound = $onefound"
done <<EEE
A B C
AA BB CC
AAA BBB CCC
EEE
echo "end onefound = $onefound"
}
loop_function
Yvan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2