An Egyptian student in California has agreed to return to Cairo after he wrote a threatening comment on Facebook about Donald J. Trump that drew the attention of the Secret Service and led to the cancellation of his student visa, according to law enforcement officials and his lawyer.

Emadeldin Elsayed, 23, posted an article on Facebook last month about Mr. Trump’s proposal to bar Muslims from entering the United States. “I literally don’t mind taking a lifetime sentence in jail for killing this guy, I would actually be doing the whole world a favor,” he wrote, according to his lawyer, Hani Bushra.

After the Secret Service investigated his comments, Mr. Elsayed was expelled from flight school, which made him ineligible to continue studying in the country on a visa, even though prosecutors decided not to charge him. Rights advocates say they are alarmed by his case and see it as another sign of the U.S. government using the immigration system as a punitive tool against people, particularly Muslims, who are perceived as threats.

An immigration judge last Friday granted Mr. Elsayed a voluntary departure, a form of repatriation that spares him a formal deportation but returns him to Egypt escorted by federal agents, said Virginia Kice, a spokeswoman for Immigration and Customs Enforcement. Lawyers said it would be difficult for him to return.