MacOS – running a command stored in a bash variable

bashmacos

So I'm trying to capture the IP address of a Parallels VM guest (Win8) from the host (OS X). I thought a bash script would be good for this. The ultimate goal is to have a single command that will fetch the IP address and then initiate an ssh port redirect.

I am aware of the prlctl enter command, and I do not believe it supports port redirection.

My script thus far:

#!/bin/bash

VM="Win8 Dev"
CMD="prlctl exec \"$VM\" ipconfig | grep "IPv4" | grep -m1 -o '\d\{1,3\}\.\d\{1,3\}\.\d\{1,3\}\.\d\{1,3\}'"
echo $CMD
IP=$($CMD)
echo $IP

output:

prlctl exec "Win8 Dev" ipconfig | grep IPv4 | grep -m1 -o
'\d\{1,3\}\.\d\{1,3\}\.\d\{1,3\}\.\d\{1,3\}' Failed to get VM config:
The virtual machine could not be found. The virtual machine is not
registered in the virtual machine directory on your Mac. Contact the
Parallels support team for assistance.

So it appears that the CMD variable is being populated correctly, but something is getting lost when trying to assign the output of the command to the IP variable.

Any thoughts on what I am doing wrong?

Best Answer

If anyone else needs to do this, here is the solution I came up with:

#!/bin/bash

VM="name of my VM"
CMD="prlctl exec \"$VM\" ipconfig | grep "IPv4" | grep -m1 -o '\d\{1,3\}\.\d\{1,3\}\.\d\{1,3\}\.\d\{1,3\}'"
IP=$(eval $CMD)

#once you have the correct data in the $IP variable you can do something with it.. I initiate an ssh session, but you can do whatever you like.

I have no idea why eval is needed here. Someone more familiar with bash will be needed to answer that mystery.