Parsing Command Output in Bash Script

13,256

Solution 1

The reason for the error is that

done < $cmdout

thinks that the contents of $cmdout is a filename.

You can either do:

done <<< $cmdout

or

done <<EOF
$cmdout
EOF

or

done < <(mycommand)    # without using the variable at all

or

done <<< $(mycommand)

or

done <<EOF
$(mycommand)
EOF

or

mycommand | while
...
done

However, the last one creates a subshell and any variables set in the loop will be lost when the loop exits.

Solution 2

"How can I read a file (data stream, variable) line-by-line (and/or field-by-field)?"

"I set variables in a loop. Why do they suddenly disappear after the loop terminates? Or, why can't I pipe data to read?"

Share:
13,256
Mr Shoubs
Author by

Mr Shoubs

Hello, A Software Developer for BTC Solutions, spend my day keeping a shipload of pirates in order. http://uk.linkedin.com/pub/daniel-shoubridge/13/338/470/

Updated on June 11, 2022

Comments

  • Mr Shoubs
    Mr Shoubs almost 2 years

    I want to run a command that gives the following output and parse it:

    [VDB VIEW]
    [VDB] vhctest
            [BACKEND] domain.computername: ENABLED:RW:CONSISTENT
            [BACKEND] domain.computername: ENABLED:RW:CONSISTENT
            ...
    

    I'm only interested in some key works, such as 'ENABLED' etc. I can't search just for ENABLED as I need to parse each line at a time.

    This is my first script, and I want to know if anyone can help me?

    EDIT: I now have:

    cmdout=`mycommand`
    
    while read -r line
    do
       #check for key words in $line
    done < $cmdout
    

    I thought this did what I wanted but it always seems to output the following right before the command output.

    ./myscript.sh: 29: cannot open ... : No such file

    I don't want to write to a file to have to achieve this.

    Here is the psudo code:

    cmdout=`mycommand`
    
    loop each line in $cmdout
       if line contains $1
           if line contains $2
                output 1
           else
                output 0