Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Two difference scenario in bash program,

First

Here i am breaking loop in function testFunc.

#!/bin/bash

function testFunc {
    if [ some condition ] ; then
        break
    fi
}

while [ 1 ]
do
    testFunc
done

Second :

In this case, testFunc will return some value, and handling the loop from that value.

#!/bin/bash
function testFunc {
    FUNC_RET=0
    if [ some condition ] ; then
        FUNC_RET=1
    fi
}

while [ 1 ]
do
    testFunc
    if [ 0 == $FUNC_RET]; then
        break
    fi
done

So, which is ideal or proper way to implement this concept.? testFunc may be written in some other script also. Hope this is not one of silly questions.

share|improve this question
    
I can't see a reason from your examples why it should not possible to skip the if and use while [ condition ]...is there a reason? –  Bobby Jan 27 at 15:04
1  
Thts because, we write whole script logic inside do...while loop, so more than one code blocks will be there in loop. and testFunc may belong to different script also. –  KisHan SarsecHa Gajjar Jan 28 at 5:13
add comment

2 Answers

Putting the break in the function is needlessly "action at a distance"

I would have the testFunc return the success/failure exit status of the condition it's testing.

#!/bin/bash

function testFunc { [[ some condition ]]; }

while true
do
    : do stuff ...
    testFunc && break
done

But that just cries out for

while ! testFunc
do
    : do stuff ...
done
share|improve this answer
add comment

The other reason not to have testFunc send a break is that it makes testFunc unusable anywhere else in the code not inside a while loop. As a general rule functions in any language should avoid side effects and only interact via their arguments and return values.

share|improve this answer
    
+1 for first line...function will be not usable anywhere. –  KisHan SarsecHa Gajjar Jan 28 at 5:17
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.