Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 ???

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