Assuming you have it just as a string, in the format shown in the code block in your initial question (i.e. "ubuntu server" foo bar
), and the data is known to be sufficiently nice, i.e. only quoted strings (no shell special characters), you could use eval
to evaluate it is as part of a shell command:
str='"ubuntu server" foo bar'
eval "arr=($str)"
With that input, this would give the array arr
with the three elements ubuntu server
, foo
, and bar
. You can use the array in the usual ways, e.g. "${arr[@]}"
to expand to a list of words, one for each element.
But note that using eval
involves evaluating the value for all shell syntax, not just quotes. E.g. if the string contains a command substitution $(cmd...)
, that command will run. If the string contains the unquoted );
, it'll end the compound assignment statement, and what comes after will run as a shell command.
To be on the safe side, validate the input first, e.g. by checking it only contains quotes and safe characters. E.g. this would allow letters, numbers, blanks, the underscore and the two types of quotes, all of which should be safe here. The input could still have unmatching quotes, which would cause an error on the eval
.
re='[^[:alnum:][:blank:]_'\''"]'
if [[ "$str" =~ $re ]]; then
echo "unsafe input" >&2
else
eval "arr=($str)";
if [[ $? -ne 0 ]]; then
echo "error in assignment" >&2
fi
fi
vboxmanage list vms
that you want to have? The names of the VMs in a list? To iterate over?vmboxmanage list vms
does not contain three words, it always seems to contain two words, a quoted virtual machine name and an UUID. It would be very nice if you could show real data. There will be two fields for each available VM.