Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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
share|improve this question
    
My answer to a related question. The "stdin vs. command line" split is the same, but you don't really use xargs in functions. –  Rich Homolka Apr 24 '13 at 17:32
    
@Homolka, thanks for helping. Nice answer –  ravnur Apr 24 '13 at 19:18
add comment

1 Answer 1

up vote 3 down vote accepted

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
}
share|improve this answer
    
Nice addition, Spack! –  Doug Harris Apr 24 '13 at 17:31
    
thanks for helping –  ravnur Apr 24 '13 at 19:17
    
$(...) should be preferred to `...` –  evilsoup Apr 30 '13 at 10:54
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.