RIO DE JANEIRO — Just over four months ago, Jair Bolsonaro was fighting for his life after being stabbed in the gut during a presidential campaign rally. On Tuesday, after a quick recovery and an unlikely victory, he was sworn in as Brazil’s president, steering Latin America’s largest nation far to the right in a political shift that was evident even during his inauguration.

As he addressed a crowd from the presidential palace amid unusually tight security that underscored his worry about a new assassination attempt, Mr. Bolsonaro waved a Brazilian flag and proclaimed that on that day, Brazilians were “being freed from socialism.”

The country’s flag “would never be red again,” he said, alluding to the rival Workers’ Party as he stood next to his wife and Vice President Hamilton Mourão, “even if it takes our blood to keep it green and yellow.”

The Workers’ Party, which had won the last four presidential elections, was crushed in the October vote after the country slipped into recession, violence soared and corruption scandals tarred much of the elite. It boycotted the swearing-in ceremony, reflecting the lingering bitterness of a presidential race that polarized Brazilians like none other in recent history.