Say I have 2 variables that I am assigning as follows:

psaux=`ps aux | grep someProcessName`
pscount=`ps aux | grep someProcessName | wc -l`

I would like to combine the assignments in one line, so that the "ps aux | grep someProcessName" part is only executed once, so I know there's no possibility something could change in between two executions.

The closest I can come is the following grotesque pseudocode:

read psaux pscount <<<$(ps aux | grep someProcessName | tee &1 | wc -l)

1 Answer 1


Just re-use the first variable:

psaux="$( ps aux | grep "someProcessName" )"
pscount="$( printf '%s\n' "$psaux" | wc -l )"

The command grep is called only once.
The result of such call is re-used to count lines.

  • Thank you, I can see now I was going about that all wrong. Just a note, with printf '%s', I get a line count of one less than the actual number of lines output by "ps aux | grep ..." (which is the number I'm really looking for), replacing it with "echo" gives the actual number of lines
    – User41943
    Commented May 13, 2016 at 3:13
  • Rather than echo, use printf '%s\n' "$psaux". Commented May 13, 2016 at 3:15

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .