Reputation: 5092
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.
Upvotes: 1
Views: 126
Reputation: 4465
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"
}
Upvotes: 4