1
chaouche@karabeela ~/DOWNLOADS/MUSIQUE/CD2 $ ls djavan* | awk '{print $5}' | cut -f1 -dM | sum
0
chaouche@karabeela ~/DOWNLOADS/MUSIQUE/CD2 $ sum $(ls djavan* | awk '{print $5}' | cut -f1 -dM)
158.5

chaouche@karabeela ~/DOWNLOADS/MUSIQUE/CD2 $ type sum
sum is a function
sum ()
{
    acc=0;
    for n in "$@";
    do
        acc=$(echo $acc + $n | bc);
    done;
    echo $acc
}

chaouche@karabeela ~/DOWNLOADS/MUSIQUE/CD2 $

How to make the first form work ? I like pipes.

ychaouche
  • 4,922
  • 2
  • 44
  • 52
  • 1
    possible duplicate of [Pipe output to bash function](http://stackoverflow.com/questions/11454343/pipe-output-to-bash-function) – Radu Rădeanu Jan 05 '14 at 00:14

1 Answers1

4

It seems you confuse arguments and standard input stream.

What is the meaning of "|"? Redirect standard output of left-hand command into standard input of right-hand command. So you need a function which reads standard input and not arguments. The following functions sums arguments (if any) or reads standard input, if there where no arguments given:

sum ()
{
    acc=0;
    if [ "$#" -gt 0 ]; then
        # We were given arguments
        for n in "$@"; do
            acc=$(echo $acc + $n | bc)
        done
    else
        # We read standard input line by line
        while read line; do
            acc=$(echo $acc + $line | bc)
        done
    fi
    echo "$acc"
}
TheConstructor
  • 4,285
  • 1
  • 31
  • 52