user3514616
user3514616

Reputation: 21

bash for with numerical comparison and file existence

I tried to do a for loop with 2 conditions but I didn't succeed in any way:

for (( i=0 ; -e /file && i < 10 ; i++ ))

of course I tried any combination of parentheses like:

for (( i=0 ; [ -e /file ] && [ i < 10 ] ; i++ ))

for (( i=0 ; [ -e /file -a i < 10 ] ; i++ ))

What's wrong on this? I googled a lot for this, but I didn't find any suggestion.

Upvotes: 2

Views: 71

Answers (1)

amphetamachine
amphetamachine

Reputation: 30623

You have to do some subshell trickery to pull this off:

for (( i=0 ; $([ -e /file -a $i -lt 10 ]; echo "$?") == 0; i++ ))

Or probably better:

for (( i=0 ; $([ -e /file ]; echo "$?") == 0 && i < 10; i++ ))

What's happening here is that $(...) is being run and placed into the mathematical expression ... == 0. When it's run the echo "$?" spits out the return code for [ which is 0 for no-error (i.e. expression is true), and 1 for error (i.e. expression is false) which then gets inserted as 0 == 0 or 1 == 0.

Upvotes: 4

Related Questions