I want to make a build chain script, and I don’t want it to perform until the end if there are error during compilation.
It’s the first time I write a more “elaborated” script in bash, and it just doesn’t work:
- it doesn’t echo ERROR although I have lines with the word error in it
- whatever the value of testError, the script just hangs in the line
this is the code:
testError=false
output=$(scons)
while read -r line; do
if [[ $line == .*[eE]rror.* ]] ; then echo 'ERROR' ; $testError = true ; fi #$testError = true fi
done
echo $testError
if $testError ; then exit ; fi;
... other commands
EDIT: Following all posters answers and Bash setting a global variable inside a loop and retaining its value — Or process substituion for dummies and How do I use regular expressions in bash scripts?,
this is the final version of the code.
It works:
testError=false
shopt -s lastpipe
scons | while read -r line; do
if [[ $line =~ .*[eE]rror.* ]] ; then
echo -e 'ERROR'
testError=true
fi
echo -e '.'
done
if $testError ; then
set -e
fi
You set the value of
testErrorin a subshell induced by your pipeline. When that subshell exits (at the end of the pipeline), any changes you made disappear. Try this:or, if you don’t want or can’t use process substitution, use a temporary file
This eliminates the pipeline, so the changes to
testErrorpersist after the while loop.And, if your version of bash is new enough (4.2 or later), there is an option that allows the while loop at the end of a pipeline to execute in the current shell, not a subshell.