DETROIT — The U.S. government expects to sell the last of its stake in General Motors by the end of the year, bringing an end to a sad chapter in the 105-year-old auto giant’s history.

The Treasury Department said Thursday it still owns 31.1 million shares of the auto giant, less than 2 percent. It plans to sell them by Dec. 31, as long as the price holds up.

Shares of GM briefly hit $39 in trading early Thursday. They pulled back a bit by midday, but still were up 76 cents, or 2 percent, to $38.45. The shares have gained 34 percent this year.

The government received 912 million shares in exchange for a $49.5 billion bailout during the financial crisis in 2008 and 2009.

So far, it has recovered $38.4 billion of the money, but selling the remaining shares at Wednesday’s $37.69 closing price gets the government $1.17 billion, leaving taxpayers short by roughly $10 billion.

The government says the bailouts of GM and Chrysler were needed five years ago to save the American auto industry and more than 1 million jobs. It never expected to get all of the money back.

“Had we not acted to support the automotive industry, the cost to the country would have been substantial — in terms of lost jobs, lost tax revenue, reduced economic production and other consequences,” Deputy Assistant Treasury Secretary Tim Bowler said.

Taxpayers’ initially got a 61 percent stake in GM in exchange for the bailout, which was needed because GM nearly ran out of cash and may have faced liquidation.

Treasury gradually has sold off its stake since a November 2010 initial public offering.