Purchase Linux CDs / DVDs / Flash Drives at OSDisc.com

Welcome to Our Community

While Linux.org has been around for a while, we recently changed management and had to purge most of the content (including users). If you signed up before April 23rd please sign up again. Thanks!

Problem in While loop in BASH

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

  1. santosh07bec

    santosh07bec Guest

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

    cat /tmp/instanceid.txt | while read id eip garbage
    if [ "$id" = "i-ab7178c1" ]
    ec2-start-instance -O accesskey -W key "i-ab7178c1"
    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.

  2. KenJackson

    KenJackson Guest

    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:
    function file_has_key()
        cat $1 | while read id eip garbage
            if [ "$id" = "$KEY" ]; then
                return 1;
        return 0;
    if file_has_key /tmp/instanceid.txt; then
        ec2-start-instance -O accesskey -W key "$KEY"
    echo "The flag contains value = $flag"
  3. santosh07bec

    santosh07bec Guest

    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