Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

Shell: Break both if and for loop at once.

My script: ip to name resolve code

IP=192.168.27.191
hostNameChecker()
{
    if [ `getent hosts $1 | wc -l` -ne 0 ];then
        HOST_NAME=`hostname`
        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[@]} 
        do
            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 
                else
                    continue;
                fi
        done
            echo "ERROR: Mismatch between DNS:$DNS_NAMES and Hostname:$HOST_NAME"
            exit 0  
    fi
}
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 ???

share|improve this question

2 Answers 2

up vote 5 down vote accepted

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.

share|improve this answer
    
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.

share|improve this answer
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

 
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.