During the years when Mogadishu resembled one big battlefield, U.N. and other aid workers trying to improve Somalia often lived in the comfortable, modern and largely safe capital of neighboring Kenya.

As security improved in Mogadishu in the past two years and the lives of Somalis returned to a semblance of normal, those jobs began shifting from Nairobi back to Mogadishu.

On Wednesday, a truck bomb and gunfire attack by al-Shabab, an Islamist militant group, on the main United Nations compound in Mogadishu left eight U.N. employees and five Somali civilians dead, showing just how dangerous that shift has been.

A U.N. official said Thursday that in the weeks preceding the attack, the threat level had been elevated around Mogadishu’s airport, the heart of military and diplomatic efforts in the city. The militant attack took place across the street.

A second U.N. official said that the Mogadishu operations have been under consistent threat for years but that he was unaware of a specific, elevated threat. Both U.N. officials spoke on the condition of anonymity because they are not authorized to speak publicly.

In April, al-Shabab carried out a massive attack on Mogadishu’s court complex. Britain’s Foreign Office released a travel warning on Somalia two days before.

Wednesday’s assault may give even more pause to aid workers who have hesitated to transfer their work from Nairobi to Mogadishu.

“It’s not going to make it easier to attract people to work in Mogadishu,” said Ben Parker, spokesman for the U.N. mission in Somalia. “I have not heard of anybody talking about quitting because of this incident. . . . You probably wouldn’t have taken a job in Mogadishu if you were risk-averse.”

U.N. Secretary General Ban Ki-moon, who was visiting Beijing on Thursday, expressed outrage at the “despicable” attack and said the United Nations will not be deterred from its work.

The world body is in a difficult spot in Somalia, because it must balance two competing objectives: keeping staff safe while also carrying out its mandate to promote the rule of law, human rights, women’s empowerment and the protection of children.

Assuring safety and advancing those goals are often at odds, said one of the U.N. officials who insisted on anonymity. But the Somali government has increased demands that the United Nations’ international staff work in Mogadishu, not from remote offices in Nairobi, he said.

On Thursday, U.N. staff worked to recover personal belongings from the targeted compound, including passports, but said there were no plans to abandon it.

A soldier fires a rocket-propelled grenade after gunmen attacked the United Nations compound in Mogadishu, the capital of Somalia, on June 19. (FEISAL OMAR/REUTERS)

An aid worker said many in the humanitarian community were still in shock.

“You feel it in the air,” he said. “Everyone is very sad, and some are traumatized.”

— Associated Press