If you look carefully, you’ll see a narrow constriction in the capillary tube through which the mercury travels up and down.
On its way up, the mercury has plenty of force to overcome the resistance and push through the constriction; the pressure of an expanding liquid can be quite high. (When water freezes and expands, the pressure can crack iron pipes and concrete walls.)
When you remove the thermometer from your mouth and the temperature of the bulb goes down, the mercury thread doesn’t flow back down; it remains at its highest level. The mercury is certainly contracting in the bulb, but it can’t pull the entire thread down along with it because the thread simply isn’t strong enough; the attractive forces between mercury atoms are too weak to withstand the pull.
If they were much stronger, mercury would be a solid instead of a liquid.
So instead of being pulled down into the bulb, the mercury thread breaks at the constriction like a cotton thread breaking at its thinnest point. The lower pool of mercury continues to contract down into the bulb, leaving a space (actually a vacuum) between it and the mercury that has been stranded above the constriction, like a line of freight cars that have become uncoupled from the rest of the train.
When you shake the thermometer down, you’re swinging it in a circular arc. Centrifugal force slings the mercury outward toward the edge of the circle, which is down into the bulb, thereby overcoming the friction at the constriction.