daldoy
daldoy

Reputation: 23

Grep and print to stdout at the same time in loop condition

I'm running a test every 60 seconds until it fails. It works fine but I would like to print the output of "npm test" at the same time.

until npm test | grep -m 1 "fail"; do sleep 60 ; done && say fail

I've tried using tee as in the next command but it just runs the loop once:

until npm test | tee >(grep -m 1 "fail"); do sleep 60 ; done && say fail

I'm using OS X.

Upvotes: 1

Views: 606

Answers (2)

KamilCuk
KamilCuk

Reputation: 141105

exec 3>&1; 
until npm test | tee >(cat >&3) | grep -q -m 1 "fail"; do sleep 60 ; done && say fail

exec opens new file descriptor with the number 3 which redirects it's output to file descriptor 1, which is stdout.

Then in until condition we tee the output into file descriptor 3.

You can be a smarty and save cats:

exec 3>&1; 
until npm test | tee /proc/self/fd/3 | grep -q -m 1 "fail"; do sleep 60 ; done && say fail

Upvotes: 0

Ralf
Ralf

Reputation: 1813

You could try

until npm test | tee /dev/stderr | grep -m 1 "fail"; do sleep 60 ; done && say fail

The output of npm test is tee'd to stderr. So the same text goes to stdout and stderr. Stdout is processed by grep and stderr is printed to the terminal.

Upvotes: 1

Related Questions