bash - how to exit from a find-exec loop if the command fails

in «tip» by Michael Beard
Tags: , , , , ,

how to write a find-exec loop that exits on failure

I was trying to figure this out for a command I needed to run in Grid, but, it's a useful pattern in general.

How to exit from find -exec if it fails on one of the files

The answer from Eugene Yarmash was what I really needed. It consists of:

find some/path | while read f
do
    program "$f"
    if [ $? -ne 0 ]
    then
        break
    fi
done

It only got 1 vote, but it was what I was looking for.

Here is the script that I used for Grid and stylus compiling:

#!/usr/bin/env bash
set -e

StylusExe=~/.nvm/versions/node/v10.16.0/bin/stylus

#### --------------------
#### different way of doing this, but it won't break on errors
#### --------------------
#find . -type d \( ! -name . \) -exec bash -c "${StylusExe} -c --line-numbers '{}'" \;

#### --------------------
#### this does basically the same thing, but it WILL break on errors, so ...
#### I think it's slightly better
#### --------------------
find . -type d \( ! -name . \) | while read f 
do
    ${StylusExe} -c --line-numbers "$f"
    if [ $? -ne 0 ]
    then
        break
    fi
done