Unexpected lines in bash for loop

I'm having a problem with a newline in my BASH code trying to loop over the following:

bash-4.3$ vboxmanage list vms
  "node1" {280482b5-3913-4019-aa9a-383f1f3131a1}
  "test_default_1419033096698_75346" {9a2f7b6b-33d8-4997-9c35-9b86f3d183b6}

      

Knowing that I am getting unexpected results below

for name in $(vboxmanage list vms); do
    echo "==> $name"
done

  ## Prints
  ==> "node1"
  ==> {280482b5-3913-4019-aa9a-383f1f3131a1}
  ==> "test_default_1419033096698_75346"
  ==> {9a2f7b6b-33d8-4997-9c35-9b86f3d183b6}

      

I would expect to get the following though?

  ==> "node1" {280482b5-3913-4019-aa9a-383f1f3131a1}
  ==> "test_default_1419033096698_75346" {9a2f7b6b-33d8-4997-9c35-9b86f3d183b6}

      

So I try to do this and ...

for name in "$(vboxmanage list vms)"; do
    echo "==> $name"
done

  ==> "node1" {280482b5-3913-4019-aa9a-383f1f3131a1}
  "test_default_1419033096698_75346" {9a2f7b6b-33d8-4997-9c35-9b86f3d183b6}

      

The results are displayed on one line, as expected ...

I am wondering why this is the first example, I know quite well that multiple lines should be read with while loop

. I'm more curious as to why this is being done, I'm not interested in implementation for

as a solution.

+3


source to share


1 answer


Your loop is essentially like this:

for name in "node1" {280482b5-3913-4019-aa9a-383f1f3131a1} "test_default_1419033096698_75346" {9a2f7b6b-33d8-4997-9c35-9b86f3d183b6}
do
    echo "$name"
done

      

That is, each individual word is printed in a separate iteration of your loop.



As the FAQ will tell you, use a loop instead while read

:

while read -r name
do
    echo "$name"
done < <(vboxmanage list vms)

      

As often mentioned in the FAQ, if you want to keep leading and trailing spaces, you must use IFS= while read -r name

. This clears the value of the input field separator IFS

for the duration of the command.

+6


source







All Articles