DHAKA, Bangladesh — The cook was crouching in a washroom, taking refuge from the gunmen who had invaded the Holey Artisan Bakery, when he understood that there was a logic behind the killing: The people in the restaurant were being sorted.

“Bengali people, come out,” one gunman shouted. When the cook, Sumir Barai, and eight other men opened the bathroom door, trembling, they saw two young men, clean shaven and dressed in jeans and T-shirts.

“You don’t need to be so tense,” one of the men told them. “We will not kill Bengalis. We will only kill foreigners.” At that, Mr. Barai’s gaze flicked to the floor of the restaurant, where he could see six or seven bodies, apparently shot and then sliced with machetes. All appeared to be foreigners.

The gunmen, he said, seemed eager to see their actions amplified on social media: After killing the patrons, they asked the staff to turn on the restaurant’s wireless network. Then they used customers’ telephones to post images of the bodies on the internet.

Friday night’s assault on the Holey Artisan Bakery in the diplomatic district of Dhaka, in which at least 20 hostages and two police officers were killed, marks a scaling up of ambition and capacity for Bangladesh’s Islamist militancy, which has until now carried out pinpoint assassinations, mostly of critics of Islam and members of religious minorities.