0

I want to write a simple loop like this:

for f in my_file0 my_file1 my_file2; do
    (( $(find . -name $f | wc -l > 0 ))
done

However, I want the loop to break the script if fails and print an error message, so I did this:

for f in my_file0 my_file1 my_file2; do
    (( $(find . -name $f | wc -l > 0 )) || echo error && exit 1
done

which exits at the first iteration, obviously.

So, I moved on to this solution

for f in my_file0 my_file1 my_file2; do
    (( $(find . -name $f | wc -l > 0 )) || (echo error && exit 1)
done

which, as I understand it, only exits the sub-shell :-(

So, now I write it like this:

for f in my_file0 my_file1 my_file2; do
    (( $(find . -name $f | wc -l > 0 ))
    if (( $? > 0 )); then echo error && exit 1; fi
done

but that sucks...

What can I do, beside calling a function that will run those two commands?

3
  • Use break in place of exit 1? This way you'll get out of for loop but not subshell.
    – Kulfy
    Sep 10, 2019 at 6:42
  • Please tell us what you try to ... Read this.
    – pLumo
    Sep 10, 2019 at 8:42
  • Also, please check your syntax... I'd say you're missing a closing bracket after each | wc -l. And generally speaking: a find | wc -l in a for f in files* loop is a good solution for exactly nothing.
    – pLumo
    Sep 10, 2019 at 8:44

1 Answer 1

2

Use curly braces instead of parentheses, that one doesn't spawn a new subshell:

... || { echo error; exit 1; }

Notice that – unlike with parentheses – you'll need to put a semicolon even after the last statement.

Also note that I've changed && into a ;, I think you should even exit if echo fails for whatever unlikely reason; feel free to change that back if you really wish to continue the loop if echo fails.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .