The fourth day would have belonged entirely to Pakistan but captain Babar Azam was out six overs from the end for 55 after the best partnership of the match.
That gave Sri Lanka a sniff of hope that it can still win, but the odds are with Pakistan, which needs 120 more runs with seven wickets in hand and a full day.
The highest successful run chase in Galle is 268 and Pakistan went about achieving the unlikely showing determination and skill on a pitch that slowed down and lacked bounce.
Sri Lanka made it easy with poor field placements. Despite having almost 350 runs to defend, the host spread the field early in Pakistan's innings and the batters were happy to knock off the singles and put up a solid foundation.
The openers combined for 87 runs and the start Pakistan needed, although Sri Lanka claimed the wickets of Imam-ul-Haq (35) and Azhar Ali (6) in quick succession.
First-innings century-maker Babar added 101 runs for the third wicket with Shafique to help Pakistan seize the initiative.
Shafique was unbeaten at stumps having batted for close to six hours. He'd faced 289 deliveries and hit just five fours and one six.
The second century of Shafique's six-test career could be a match-winning one. There was a nervous moment when he was on 4 and a loud lbw shout was turned down. The Sri Lankans reviewed and Shafique was narrowly saved.
Spinner Prabath Jayasuriya, Sri Lanka's main weapon, broke the partnership when he got one to spin from the rough outside Babar's leg stump and the ball clipped the off stump bail much to Babar's bewilderment. A better defensive shot using his feet could have saved him.
Vice-captain Mohammad Rizwan, 7 not out, joined Shafique and the pair ensured there were no further hiccups.
Earlier in the day, Sri Lanka's Dinesh Chandimal was left stranded on 94 when their second innings was ended on 337 with the addition of only eight runs. Jayasuriya was the last man out for 4.
The series is being played against the backdrop of an economic and political crisis engulfing Sri Lanka.
The second test, scheduled to start on Sunday, was switched from Colombo to Galle because Sri Lanka Cricket decided not to take any chances with potential political protests in the capital.
The venue switch was confirmed on Monday around the time Ranil Wickremesinghe declared a state of emergency. He became acting president last week after Gotabaya Rajapaksa fled abroad and resigned after months-long mass protests over the country's economic collapse.
SLC was forced to postpone the Lanka Premier League which was scheduled for next month due to the economic crisis. Officials also admitted the Asia Cup they were scheduled to host in late August is slipping away from them due to the crisis.