Shell: Break both if and for loop at once.

My script: ip to name resolve code

    if [ `getent hosts $1 | wc -l` -ne 0 ];then
        DNS_IP=`getent hosts $1 | cut -d " " -f 1 | sed 's/^[ \t]*//;s/[ \t]*$//'`
        DNS_NAMES=`getent hosts $1 | cut -d " " -f 2- | sed 's/^[ \t]*//;s/[ \t]*$//'`
        for DNS_NAME in ${DNS_NAMES[@]} 
            if [[ "$DNS_NAME" == "$HOST_NAME" ]];then
                    echo "Host name:$HOST_NAME and DNS_NAME:$DNS_NAME matched"
                    break 2;########Not working. only brakes inner for not outer if 
            echo "ERROR: Mismatch between DNS:$DNS_NAMES and Hostname:$HOST_NAME"
            exit 0  
hostNameChecker $IP

In the above script break 2 only breaks inner for not outer if. I can add another if to solve it but is there any other possible way ???


break has no effect on if statements. In your use case, return will have the effect you're seeking, since there are no statements after the outer if, and return exits the function.

  • Thanks it worked. I used return 0; instead of break 2; – Ram Sep 5 '13 at 13:30

In C, you would use goto, in Bash we don't have goto yet even if there was a similar language construct, this is considered harmful.

So do it using another if.

  • 2
    What does C has to do with this? – Bernhard Sep 5 '13 at 5:56
  • @Bernhard: I just tried to include a supporting piece of information. What's the problem? If you think that's inapproriate there are tools for that in SA.. – onur güngör Sep 5 '13 at 12:12
  • @Bernhard C => csh => shell - viola! – ott-- Sep 5 '13 at 21:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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