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?

oz1cz
  • 5,504
  • 6
  • 38
  • 58

4 Answers4

8

You can use:

$ alpha | xargs -d "\n" beta
yolenoyer
  • 8,797
  • 2
  • 27
  • 61
4

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

readarray -t args < <(alpha)
beta "${args[@]}"
chepner
  • 497,756
  • 71
  • 530
  • 681
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"
anubhava
  • 761,203
  • 64
  • 569
  • 643
-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
aicastell
  • 2,182
  • 2
  • 21
  • 33
  • This also subjects the output of `./alpha.sh` to pathname generation, which may not be desirable. – chepner Mar 16 '17 at 14:21
  • @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... – aicastell Mar 16 '17 at 15:58
  • It *doesn't* work, if `alpha` can output a line like `a * c`. This is not a secondary issue. – chepner Mar 16 '17 at 16:00
  • Please, can you provide an example string with echo that fails? I prefer to test it – aicastell Mar 16 '17 at 16:01
  • I just did. Read [Bash FAQ 001](http://mywiki.wooledge.org/BashFAQ/001) for more detail. – chepner Mar 16 '17 at 16:03
  • This link uses IFS as suggested in my solution – aicastell Mar 16 '17 at 16:04
  • 1
    It uses `IFS`, but not at all the way you do. Also read http://mywiki.wooledge.org/DontReadLinesWithFor, a link to which is the *very first thing* on the page. – chepner Mar 16 '17 at 16:06
  • Very useful your link, I like it. Thanks for sharing! :) – aicastell Mar 17 '17 at 07:09