The pair put on 207 for the fifth wicket as Pakistan posted 557 for eight before declaring their first innings during the tea interval at the Sher-e-Bangla stadium.
Bangladesh tottered to 107 for five in reply by stumps, still 450 runs behind and facing the daunting prospect of batting for a major part of the remaining three days to avoid defeat.
Left-arm seamer Junaid Khan set the hosts back by trapping Tamim Iqbal, who hit a double-century in the drawn first Test in Khulna, leg-before with the fourth delivery of the innings.
Wahab Riaz had Mohammad Mahmudullah fending a catch to short-leg and skipper Mushfiqur Rahim was bowled by Yasir off the last ball of the day. Shakib Al Hasan was unbeaten on 14.
More From This Section
Pakistan lost skipper Misbah-ul Haq in the day's second over, bowled by Shakib for nine, before a run had been added to the overnight score of 323 for three.
But Azhar and Shafiq denied Bangladesh another success till just before the tea break when four wickets fell in the space of 27 runs as Pakistan slipped from 530-4 to 557-8.
============
The 30-year-old Azhar, who had been rescued by a no-ball early on the first day after being caught in the slips off seamer Mohammad Shahid, hit 20 boundaries and two sixes.
Having twice fallen for 157 in his 41-Test career, Azhar moved past that score by edging off-spinner Shuvagata Hom for a boundary.
He brought up his 200 by lofting Shakib for a six, while Shafiq quietly moved to his sixth Test century with a single off left-arm spinner Taijul Islam.