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?
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.
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.