prasad
prasad

Reputation: 1302

How to use Linux pipe for Userdefined Shell Scripts

I have two user defined shell scripts:

First is Add

if [ $# -eq 3 ]
then
    sum=`expr  $1 + $2 `
    echo $sum
else
    echo "usage :$0 num1 num2"
    echo "num1 and num2 are two numbers"
    exit 1
fi

The next is Square

echo `expr $1 \* $1`

Can any one pleae tell me how to use Linux pipe for these shell scripts. I tried something like:

add 10 20 | square                         

But it is giving me the list of files in that directory.

Upvotes: 0

Views: 105

Answers (3)

rje
rje

Reputation: 6428

Using a pipe will pass the output from the first command to the stdin of the second command. You want the output to be used as arguments for the second command instead. Try xargs:

add 10 20 | xargs square

Of course you have to make sure that the output of the first command is just "10" in this case.

A little more explanation: a pipe will take the output of the first command and redirect it into the standard input stream of the second command. That means you will have to use a command like "read" (as some of the other answers do) to use the information from the input stream.

But your square script doesn't read anything from the standard input: it takes an argument instead. So we want to take the output of your first command (10) and use it as the argument for your second command. The "xargs" utility does exactly that: the standard input it receives will be passed as arguments to the square command. See https://en.wikipedia.org/wiki/Xargs.

By the way, command substitution has the same effect:

square $(add 10 20)

The syntax $(add 10 20) will run the add script and replace the expression with its output. So after running the add script the line looks like this:

square 30

And, in effect, we have again turned the output from add into an argument for square.

Upvotes: 2

chepner
chepner

Reputation: 531625

As written, you want to use command substitution, not a pipe (since square takes command line arguments, rather than reading from standard input):

square $(add 10 20)

To modify square so that add 10 20 | square works, use the read builtin:

#!/bin/bash

read input
echo $(( $input * $input ))   # No need for the external expr command

add should also write any error messages to standard error, not standard output:

if [ $# -eq 2 ]
then
    sum=$(( $1 + $2 ))
    echo $sum
else
    echo "usage :$0 num1 num2" >&2
    echo "num1 and num2 are two numbers" >&2
    exit 1
fi

Upvotes: 1

opalenzuela
opalenzuela

Reputation: 3171

You can use the "read" command to read the value from STDIN, if no parameters are specified:

val="$1"
test -z "$1" && read val
echo `expr $val \* $val`

Upvotes: 0

Related Questions