Bash – get output and return value of grep in single operation in bash

bashexit-statusgrepshell

I am writing a bash script; I execute a certain command and grep.

pfiles $1 2> /dev/null | grep name # $1 Process Id

The response will be something like:

sockname: AF_INET6 ::ffff:10.10.50.28  port: 22
peername: AF_INET6 ::ffff:10.16.6.150  port: 12295

The response can be no lines, 1 line, or 2 lines.
In case grep returns no lines (grep return code 1), I abort the script; if I get 1 line I invoke A() or B() if more than 1 line. grep's return code is 0 when the output is 1-2 lines.

grep has return value (0 or 1) and output.
How can I catch them both ? If I do something like:

OUTPUT=$(pfiles $1 2> /dev/null | grep peername)

Then variable OUTPUT will have the output (string); I also want the boolean value of grep execution.

Best Answer

You can use

output=$(grep -c 'name' inputfile)

The variable output will then contain the number 0, 1, or 2. Then you can use an if statement to execute different things.

Related Question