Problem in While loop in BASH

Discussion in 'Command Line' started by santosh07bec, Oct 1, 2012.

  1. santosh07bec

    santosh07bec New Member

    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Hi guys,

    I have written a big automation script for my company's servers. While writing script i found an issue with while loop and i am not able to find explanation for it, although i have found another way to work around it, but still i wonder what might be the reason which gives the result unexpected, Please take a look on the below piece of Bash code...

    #!/bin/bash
    flag=0
    cat /tmp/instanceid.txt | while read id eip garbage
    do
    if [ "$id" = "i-ab7178c1" ]
    then
    ec2-start-instance -O accesskey -W key "i-ab7178c1"
    flag=1
    break
    fi
    done
    echo "The flag contains value = $flag"

    Its a small part of my code which i wanted to use to automate the starting of instances.

    Assume that the if condition is fine and satisfies the condition once while executing the code and there in no problem the "ec2-start-instance" command, we can expect that the output of the echo as "The flag contains value = 1"; but if u execute the above code, you wont get value of the flag variable as 1 ever it will always print 0 irrespective of if condition.

    Can anybody explain why it is so.

    Thanks in advance.


    Regards,
    Santosh
  2. KenJackson

    KenJackson Active Member

    Messages:
    129
    Likes Received:
    27
    Trophy Points:
    28
    Indeed! You've found a feature of bash that I stumble over occasionally and annoys me a lot.
    It's something to do with piping into the loop. It seems to make it a separate process or something.

    I solve it by putting the loop in a function. I didn't test this, but it looks like it should work:
    Code:
    #!/bin/bash
    
    KEY=i-ab7178c1
    
    function file_has_key()
    {
        cat $1 | while read id eip garbage
        do
            if [ "$id" = "$KEY" ]; then
                return 1;
            fi
        done
        return 0;
    }
    
    flag=0
    if file_has_key /tmp/instanceid.txt; then
        ec2-start-instance -O accesskey -W key "$KEY"
        flag=1
    fi
    
    echo "The flag contains value = $flag"
  3. santosh07bec

    santosh07bec New Member

    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    KenJackson, thanks for your response :)

    We can work-around this problem in so many ways, one of which you have provided.

    I actually wanted to know the reason why its happening here.
    As you said it may be problem with the pipe, but what is the problem exactly?

Share This Page