Leon Goretzka scored late to keep Germany in the European Championship after a 2-2 draw against Hungary on Wednesday.
Jamal Musiala made an immediate impact after coming on in the 82nd minute, eluding three defenders to give Timo Werner room to shoot. Werner was blocked but the rebound fell for Goretzka, who shot past goalkeeper Peter Gulacsi in the 84th.
It had looked like Adam Szalai was going to drag his team into the round of 16. The Hungary captain scored one goal early against the run of play and set up Andras Schafer to make it 2-1 right after Kai Havertz had equalized for Germany.
Germany made the better start but was caught out early yet again in the tournament when Szalai met Roland Sallai's cross with a flying header on a counterattack in the 11th.
Germany struggled against Hungary's defensive 5-3-2 formation and was further hampered by heavy rain from a thundershower in the first half.
The home team finally made a breakthrough in the 66th when the normally excellent Gulacsi failed to punch away Toni Koos' free kick. Mats Hummels headed the ball forward and Havertz made sure from close range.
But Hungary replied immediately when Szalai played in Schafer to head the ball past Manuel Neuer.
It would have been enough to send Hungary through to the next round at Germany's expense, but substitutes rescued the game.
Germany finished second in the group with four points and will next face England at Wembley Stadium on Tuesday.
Portugal drew with France 2-2 in the other group and both progress, while Hungary finished last with two points and has been eliminated.
(For more sports news and updates, follow Ahram Online Sports on Twitter at @AO_Sports and on Facebook at AhramOnlineSports.)