1

I have the following code. In all cases I'm expecting to get 1 1. Could someone explain why I do not get the expected output in the first case?

The question seems to be very simple and I think I'm missing something basic.

Thanks in advance.

#!/bin/bash

f(){
    echo $1
}
ff(){
    echo $1 $1
}

# expecting 1 1, but got empty      
f 1 | ff

# ok
X=$(f 1)
ff $X
1
  • My answer to a related question. The "stdin vs. command line" split is the same, but you don't really use xargs in functions. Commented Apr 24, 2013 at 17:32

1 Answer 1

3

In your example that doesn't work, the pipe sends stdout of your first function f to the stdin of your second function ff. The function ff is not processing its stdin; it's processing arguments passed to it.

Here's a way to make the first line work:

ff `f 1`

The backquotes execute the f 1 and the resulting value is passed as an argument to ff.

You may also use read if you want to read the input:

ff()
{
  while read in
  do
    echo $in $in
  done
}
2

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .