0

Thank you for your patience I am new to linux and I wanted some help understanding how I can parse the output of the cut command.

So, currently I have a variable

x=$(discover nginx --human=nood | cut -f1,6)

So my output to echo "$x is a list of like

instanceID IPAddress

In my program I want to run a for loop over each row of x and extract the first and the second variables separately. Eg: if it was an array a[0] = instanceID and a[1]= IPAdderess

Please can someone guide me how to extract the elements separately. I know that I can run a loop in $x and do a cut within that but I am looking to understand if there is a better way of doing it.

Shivangi Singh
  • 111
  • 2
  • 4

1 Answers1

0

For that, you don't need to store the data in a variable at all, a loop over the output of discover will do:

discover nginx --human=nood | cut -f 1,6 |
while read -r instanceID IPAddress; do
    # Use "$instanceID" and "$IPAddress" here
done

Alternatively, in bash or a shell that understands process substitutions (<( ... )):

while read -r instanceID IPAddress; do
    # Use "$instanceID" and "$IPAddress" here
done < <( discover nginx --human=nood | cut -f 1,6 )

The difference between these two is only visible if you want to carry the values of some variable out of the loop. In the first example, the loop will run in a subshell and you would therefore not be use any values of variables that set inside the loop after the loop (they exists in their own local environment).

In the second example, no subshells are involved (except for the one that runs the process substitution with discover and cut), so values of variables are accessible after the loop.

Kusalananda
  • 333,661
  • I am trying to write a bash script that uses a variable that already has the x=$( discover nginx --human=nood).

    When I try "$x" |cut -f1,6 | while ... I get an error of command not found

    – Shivangi Singh Nov 25 '19 at 17:45