Take the 2-minute tour ×

I've got the following if clause:

if $(echo "$INDEX" | grep -c '^?? ' &> /dev/null) > 0 ;

It outputs count of strings matching grep expression. How can I assign that count to a variable inside an if clause, so that I don't have to execute that command twice to get count of strings?

share|improve this question

4 Answers 4

up vote 1 down vote accepted

You assign the result of a (series of) command to a variable like this:


and then call it when it's needed like this: $matchedCount

share|improve this answer
Yep, sorry, my question was pretty dumb –  Max Al Farakh May 13 '11 at 8:22
I'm not so sure I've understood it correctly though... :P –  Alberto Zaccagni May 13 '11 at 8:24

There are no operators to both assign and test at the same time in zsh like there are in some languages, but you don't have to run the operation twice. Instead of testing on the full command, test on an already assigned variable, then if your test comes back true you have the variable ready to go. If not you haven't wasted any cycles.

if (( index_count > 0 )); then
    # Do your thing with $index_count
share|improve this answer
Updated the if statement -- proper syntax for the arithmetic operation. –  glenn jackman May 13 '11 at 14:00

You can perform an assignment inside an arithmetic expression and use the result in a test. This works in ksh, bash and zsh.

if ((n = $(echo "$INDEX" | grep -c '^?? ' &> /dev/null))); then
  echo "\$n is not zero"

However, for the sanity of people reading your code (including you in three months), I don't recommend including assignments in a test that way. As others advise, assign to a variable first, then test the result of the assignment.

share|improve this answer

You can't, reliably. Assign first, then test.

share|improve this answer

Your Answer


