Shafiq scored an unbeaten 86 while skipper Ahmed was 57 not out as they lifted Pakistan from a perilous position at 52-5 to 198-5 at close after being set a daunting target of 317.
The pair added 146 for the unbroken sixth-wicket stand to leave Pakistan needing another 119 runs with five wickets in hand to level the series. Sri Lanka won a nail-biting first Test in Abu Dhabi by 21 runs.
Both Shafiq and Ahmed batted confidently to raise hopes of Pakistan maintaining their unbeaten record in nine Test series in the United Arab Emirates, their adopted home since 2009.
Pakistan have been forced to play at a neutral venue since a 2009 terror attack on the Sri Lankan team prompted authorities to suspend international cricket in the country.
Earlier, paceman Wahab Riaz grabbed four for 41 and left-arm spinner Haris Sohail took three wickets in a single over to dismiss Sri Lanka for 96 in their second innings, after they resumed on 34-5.
Shafiq brought up his 19th Test fifty with a well-timed cover drive off fast bowler Suranga Lakmal, his first 50-plus score in 12 innings.
Ahmed smashed part-timer Kusal Mendis for his fourth boundary to complete his 14th Test half-century.
It was off-spinner Dilruwan Perera who ripped apart Pakistan with a triple strike in the second session. He dismissed Haris Sohail (10), Shan Masood (21) and Babar Azam (nought) to leave Pakistan in tatters at 52-5.
He could have claimed the wickets of both Shafiq, on 26, and Ahmed, on 22, but both were dropped by Mendis at short leg off successive balls, leaving Sri Lanka to rue the missed chances.
Pakistan made a disastrous start when opener Sami Aslam fell for one, caught in the slips off Lahiru Gamage.
Masood and Azhar Ali (17) added 31 for the second wicket before the batting collapse began with Ali caught off fast bowler Nuwan Pradeep for 17.
Pakistan had needed to make early inroads in the morning and Riaz provided them with the important wicket of Niroshan Dickwella in the fifth over of the day for 21.
Leg-spinner Yasir Shah dismissed Perera for nought to leave Sri Lanka in danger of being all out for their lowest ever total of 71 against Pakistan.
But Mendis (29) and Rangana Herath (17) added 35 for the eighth wicket to frustrate Pakistan before Sohail struck thrice in his only over to give his team hope of an upset win.
First Published: October 9, 2017, 11:54 PM IST