1

code for /usr/local/bin/sayHi

echo hi $1

Now in Terminal, if I run sayHi John, it will output hi John

If I want to run echo John | sayHi, to have the same output hi John, how can I do that?

2 Answers 2

2

A pipeline feeds data to standard input. You do not get standard input as an argument. It is simply the standard input.

To get what you want from that script you could use:

echo hi ${1:-$(cat)}

That will use the first argument if there is one and fall back to using cat to read standard input otherwise.

As cat reads from standard input if no file arguments are supplied and produces that as output (on standard output).

The ${1:-...} syntax is Shell Parameter Expansion for use $1 if it has a non-empty value otherwise use ....

Note: This will "hang" (in cat) if no arguments are supplied and not data is supplied on standard input.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer. Can you explain the dash in ${1:-$(cat)}?
1

Good question. If you want your bash script to use input send via a pipe, you have to read it in from stdin.

Currently, your script is looking for input passed as an argument to the program. The $1 construct is the first argument following your script. The arguments are white space delimited.

To get input from stdin call the read function.

#!/bin/bash
read
echo hi $REPLY

$REPLY is the default location read puts things in.

1 Comment

Sure. You can use your own variable if you want: read MyVar echo $MyVar

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.