Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

How can I store the result of grep -c as an integer in a shell variable?

This:

check=sudo virsh list |egrep -c '\b[0-9]{2}\b'

only gives me the number of matches and prints it on screen whereas the value of check is NULL.

If I execute :

check=`sudo virsh list |egrep -c '\b[0-9]{2}\b'`

I get an error that says

./test: 1 :Not found

where 1 is the number of matches.

share|improve this question
    
I fixed your markup, since the forum code borked your code examples as they were. Note the comment on David's answer: you have probably accidentally entered a space character somewhere around the = sign in the second example. A minimal example is to test: check=`echo 1`, which works, and then check= `echo 1` which returns bash: 1: command not found (or technically runs a command named "1" if it exists in the path). –  Daniel Andersson Aug 6 '13 at 15:21

1 Answer 1

Like this:

check=$(sudo virsh list | egrep -c '\b[0-9]{2}\b')

$(command) behaves like a variable where the value is the output of command.

share|improve this answer
1  
Note that it is very important not to have spaces around the = sign -- from the error description, it sounds like that may be part of the original problem. –  Gordon Davisson Aug 6 '13 at 14:47

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.