How did you determine it's the grep that "does not work"? Perhaps $node doesn't contain what you think it does? Or contains something special to the shell? Or perhaps what you're looking for isn't in the first $max lines you're examining?
Do you get a different result if you run the command from the command line?