Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing Command Output in Bash Script

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
like image 541
Mr Shoubs Avatar asked Feb 25 '23 18:02

Mr Shoubs


1 Answers

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.

like image 109
Dennis Williamson Avatar answered Mar 07 '23 09:03

Dennis Williamson