Generating a report from bash output

I am currently trying to write a script in Bash that can run a set of unit/integration tests. I have that part working, but what I need now is to be able to output a summary at the end. I have been trying to use grep ot grab every line which contains a number followed by the string failing, save it in a variable, and print it at the end.

So an example of a failing output is

224 passing (3m)
47 failing

What I would like to be printed at the end is something along the lines of

service01 4 failing
service03 1 failing

What I have so far is:

OUTPUT=""
for service in ${array[*]}
do
  echo $service
  if [ $DO_API == 'true' ]
  then
    echo 'running API tests'
    OUTPUT+="$service API $(docker exec -it $service npm run api_test | tee /dev/tty | grep -e '[0-9]+ failing' )"
  fi

  if [ $DO_CI == 'true' ]
  then
    echo 'running CI tests'
    OUTPUT+="$service CI $(docker exec -it $service npm run ci | tee /dev/tty | grep -e '[0-9]+ failing' )"
  fi
  echo $'n'
done

The above script shows no output when there are failing tests, which leads me to believe it is my grep syntax at fault.

What am I doing wrong?

Answer

The following grep command will return the required output:

grep -E '[0-9]+ failing'

The pattern [0-9]+ matches one or more digits. The -E option must be used so that grep can interpret the pattern as an extended regular expression. The + quantifier is not defined as part of the basic regular expressions.

Sample run (using a file):

$ cat testfile
224 passing (3m)
47 failing

$ grep -E '[0-9]+ failing' testfile
47 failing

As an aside, this pattern can also be implemented using basic regular expressions (BRE) in the following manner:

$ grep '[0-9]{1,} failing' testfile
47 failing

In this case, the {n,m} quantifier is used to match one or more digits. The backslashes are required to give the curly braces their special meaning.

Leave a Reply

Your email address will not be published. Required fields are marked *