I remember a quantum mechanics lecture where my professor said "Two matrices $A, B$ which commute with a third matrix $C$, $[A,C]=[B,C]=0$, commute with each other: $[A,B]=0$." I pointed out the identity $C=\mathbb{I}$ as an obvious counterexample, to which he restated the proposition to exclude my counterexample:
"Two matrices $A, B$ which commute with a third matrix $C\neq\mathbb{I}$, $[A,C]=[B,C]=0$, commute with each other: $[A,B]=0$."
He said further that he didn't know if this was a theorem, but he had never come across a counterexample. Thinking about it now, a straightforward exception is a block diagonal $C$ which is the identity in a given block, but not the other blocks so $C\neq\mathbb{I}$, and $A,B$ which are only nonzero in the given block.
My question is whether, apart from these trivial cases, transitivity of the commutator is generally true or not? If not what is a counterexample? If it is generally true for matrices how far can it be extended to other systems?
If the eigenvalues of $C$ are all simple, then the only matrices that commute with $C$ are polynomials in $C$ and your instructor's claim is correct. If the eigenvalues of $C$ are not all simple, then claim can be false, as your example shows. You could generate further examples by taking $C$ to be diagonal with at least two diagonal entries equal.
Physicists often assume that the Hermitian matrices that correspond to a quantum mesurement have only simple eigenvalues.