-1

I am making a bash script where I need to wait for a reply from a command which matches a string; until then, we need to run the below command. Once we get it, I need to assign that reply to a variable.

The command is as below

/bin/oci --profile $USER compute instance list-vnics --instance-id $INSTANCEOCID | grep -oP 'ocid1.vnic[^"]+'

the reply will come as example

ocid1.vnic.oc1.ap-mumbai-1.amaaaaaakfvuezyaagala7nf53zeomzarbf2h24a2lynp7sgin7ujrkr7jla

Once I get this reply, I need to assign it to a variable VNIC so later in script it can be called as echo $VNIC

How can I do that?

Jeff Schaller
  • 66,199
  • 35
  • 114
  • 250
ph3ro
  • 378
  • 2
  • 12

2 Answers2

1

grep will return with a true exit status when it finds at least one matching line. So here you could just do:

until
  VNIC=$(
    /bin/oci --profile "$USER" \
      compute instance list-vnics --instance-id "$INSTANCEOCID" |
      grep -oP 'ocid1.vnic[^"]+'
  )
do
  continue # or sleep 1 or other delay to avoid running again
           # straight away.
done
Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
0

Use var=$( command ) to have the stdout output of command stored in var, so in your case:

VNIC=$( /bin/oci --profile $USER compute instance list-vnics --instance-id $INSTANCEOCID | grep -oP 'ocid1.vnic[^"]+' )
Andre Beaud
  • 406
  • 1
  • 6
  • I need to execute that command & wait till I get that value. how can I loop it? – ph3ro Aug 28 '22 at 13:58
  • The exit code will be set by grep, since it is the last command to run. So if the command can complete without finding the string, and say you want to wait 10 seconds to check again, you can do: 'until VNIC=$( same as before... ); do sleep 10; done` – Andre Beaud Aug 28 '22 at 14:21