What happens when a baby sleeps and shakes his head and scratches his ears?

There may be sweating or localised itching, such as eczema, external ear canal fungal disease, etc., or there may be acute suppurative otitis media, making the infant feel uncomfortable during sleep. The frequency of head shaking during sleep should be carefully observed.
Watch the external auditory canal for redness or swelling, or pus flow. Seek medical attention if necessary.