A reprise of their 49 all out in the series opener looked a distinct possibility as they crumbled to 33 for four against the new ball but Younus' 21st Test ton and a third from Shafiq turned the tables in dramatic fashion as the duo added 219.
The Proteas took less than 17 overs to dismiss Mohammad Hafeez, Nasir Jamshed, Azhar Ali and Misbah-ul-Haq but had to wait until the 89th over to add Younus' wicket as Pakistan reached 253 for five at the close.
Younis faced 226 balls for his 111, while Shafiq will resume on Friday morning having made the same score from two more deliveries.
Dale Steyn and Vernon Philander started well after Graeme Smith had won the toss, with the latter making the breakthrough in the eighth over. Philander first had Jamshed dropped by Faf du Plessis at gully but dismissed him for three with the very next delivery when AB de Villiers gathered a simple catch behind the stumps.
Mohammad Hafeez scored the first boundary of the day off the 58th ball and moved along to 17 by the time Steyn sent him back with the first ball of his second spell. A testing line and a hint of away movement produced the edge and Smith took a low catch at slip.
Morne Morkel then stepped up to see off Azhar and captain Misbah in the space of five balls.
Azhar drove airily at one to hand De Villiers a second catch and Misbah followed for a duck, fending a hostile ball to short leg.
Pakistan were reeling but they found two men willing to take up the fight in Younis and Shafiq.
Philander struck with 12 balls left before stumps. His initial appeal appeared to be for lbw but the TV umpire detected an inside edge, making De Villiers' low take decisive.