Rafi Kamal
Rafi Kamal

Reputation: 4600

How to print each word returned from shell expansion on a separate line?

When we use shell expansion, it gives all the expanded word in one line. For example:

#!/bin/bash 
data="Hello\ {World,Rafi}"
eval echo $data

This produces the following output:

Hello World Hello Rafi

Is it possible to output each line on a separate line like this?

Hello World 
Hello Rafi

Upvotes: 3

Views: 720

Answers (6)

gniourf_gniourf
gniourf_gniourf

Reputation: 46823

Instead of using eval (which is dangerous and really not a good practice — see my comment in your post), another strategy would be to use an array. The following will do exactly what you want, in a clean and safe way:

data=( "Hello "{World,Rafi} )
printf "%s\n" "${data[@]}"

Upvotes: 1

doubleDown
doubleDown

Reputation: 8398

If I understand you right, you want to generate multiple words using brace expansion ({...}), then print each word on a separate line.

If you don't absolutely have to store "Hello\ {World,Rafi}" in a variable, you can do this with printf shell-builtin

printf "%s\n" "Hello "{Rafi,World}

Some explanation:

The format string (here: %s\n) is reused until all the arguments to printf is used up (Reference).

  1. %s\n consumes 1 argument

  2. "Hello "{Rafi,World} returns 2 words/arguments i.e. "Hello Rafi" and "Hello World"

  3. So, this printf command is equivalent to

     printf "%s\n%s\n" "Hello Rafi" "Hello World"
    

    except you don't have to type all that up.

Upvotes: 5

Antarus
Antarus

Reputation: 1621

#!/bin/bash
data="Hello\ {World'\n',Rafi'\n',Kamal'\n'}"
eval echo -e "$data"

echo -e will evaluate newline characters.

Upvotes: 3

thefourtheye
thefourtheye

Reputation: 239473

Same as Antarus'a answer, except that echo has "-n". From http://unixhelp.ed.ac.uk/CGI/man-cgi?echo

-n do not output the trailing newline

#!/bin/bash
data="Hello\ {World,Rafi}'\n'"
eval echo -n -e "$data"

Upvotes: 3

Grzegorz Żur
Grzegorz Żur

Reputation: 49181

It is different solution but a very clean one.

#!/bin/bash

names="World Rafi"
for name in $names
do
    echo Hello $name
done

Upvotes: 1

Matthias
Matthias

Reputation: 8180

Actually, your problem is not the expansion but the echo command. Depending on your system, you might get what you want by

#!/bin/bash
data="Hello\ {World\\\\n,Rafi}"
eval echo -e "$data"

Upvotes: 1

Related Questions