4

Assume that the command alpha produces this output:

a b c
d

If I run the command

beta $(alpha)

then beta will be executed with four parameters, "a", "b", "c" and "d".

But if I run the command

beta "$(alpha)"

then beta will be executed with one parameter, "a b c d".

What should I write in order to execute beta with two parameters, "a b c" and "d". That is, how do I force $(alpha) to return one parameter per output line from alpha?

4 Answers 4

8

You can use:

$ alpha | xargs -d "\n" beta
Sign up to request clarification or add additional context in comments.

Comments

4

Similar to anubhava's answer, if you are using bash 4 or later.

readarray -t args < <(alpha)
beta "${args[@]}"

Comments

2

Do that in 2 steps in bash:

IFS=$'\n' read -d '' a b < <(alpha)

beta "$a" "$b"

Example:

# set IFS to \n with -d'' to read 2 values in a and b
IFS=$'\n' read -d '' a b < <(echo $'a b c\nd')

# check a and b
declare -p a b
declare -- a="a b c"
declare -- b="d"

Comments

-1

Script beta.sh should fix your issue:

$ cat alpha.sh
#! /bin/sh
echo -e "a b c\nd"

$ cat beta.sh
#! /bin/sh
OIFS="$IFS"
IFS=$'\n'
for i in $(./alpha.sh); do
    echo $i
done

8 Comments

This also subjects the output of ./alpha.sh to pathname generation, which may not be desirable.
@chepner. Minus one, why? It's a simple example to show how to fix the issue, and it works. Obviously alpha.sh can be on the PATH directories and then you could avoid "./", but I wanted to focus the attention on fixing the issue and not on secondary issues...
It doesn't work, if alpha can output a line like a * c. This is not a secondary issue.
Please, can you provide an example string with echo that fails? I prefer to test it
It uses IFS, but not at all the way you do. Also read mywiki.wooledge.org/DontReadLinesWithFor, a link to which is the very first thing on the page.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.