He did sell the stock, like $23 billion worth. He entered the agreement to buy Twitter to show that he had another use for that cash, so that Tesla investors didn’t get spooked and sell off when they see the biggest shareholder selling (along with the downward price pressure that comes from selling a significant percentage of a company’s stock).
There was some speculation at the time that he entered the agreement with Twitter with no intention to close, just to cover his desire to cash out of Tesla at its high. Then the courts actually held him to that.