MOGADISHU — A gun battle that raged for nearly 20 hours in the capital of Somalia as soldiers battled to dislodge Islamist militants holed up in a building next to a hotel they had bombed ended on Friday with all of the attackers killed, the police said.

The militants, from the Shabab extremist group, set off two car bombs on Thursday: one outside the Hotel Makkah al-Mukarammah on a busy street in Mogadishu where Somalis were dining at restaurants, and another near the home of Appeals Court Chief Judge Abshir Omar.

The blasts and shooting killed at least 29 people and injured 80 others; officials said the toll was expected to rise.

After the explosions, the attackers retreated to an adjacent building from where they fired on soldiers who tried to enter. A police captain, Mohamed Hussein, told The Associated Press that two of the dead were soldiers.