Shafiq scored an unbeaten 86 while skipper Ahmed was 57 not out as they lifted Pakistan from a perilous position of 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 bus in Lahore prompted authorities to suspend international cricket in the country.
Pakistan on the verge of series whitewash
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.
Pakistan head coach Mickey Arthur is hopeful his team can claw their way to a famous win.
“The first session will be fantastic,” said Arthur, under whom Pakistan have lost 10 Tests and won six. “We have seven overs to the second new ball so we have to cash in on them and hope that Asad and Sarfraz see us through.”
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.
Perera could have claimed the wickets of 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.
Karunaratne misses double ton but SL in command against Pakistan
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 -- they were skittled for just 71 against Pakistan in 1994.
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.
COMMENTS (1)
Comments are moderated and generally will be posted if they are on-topic and not abusive.
For more information, please see our Comments FAQ