Upvote:2
Yes. When you arrive in Spain, you will pass through immigration control for the Schengen area regardless of whether you plan to leave the airport or not. In other words, to get to your flight to Greece, you will go through passport control. Once you've been stamped into the Schengen area, you can leave and reenter the airport.
Your flight from Spain to Greece is an "internal" Schengen flight, so there is no systematic passport control, although police or other authorities may ask to see your documents at any time. If that happens, however, they will not stamp your passport.