The expression is used superstitiously to avert the possibility that something just mentioned (if bad) might not occur, or (if it is a good thing) might occur. The action may or may not be performed, depending on how literally the speaker adheres to the superstition. If it is taken literally, it is usual to attempt physically to touch some wooden object whilst, or shortly after, exclaiming touch wood. Failure to find and touch a wooden item within a short time may be considered ominous, and cause mental distress to the person involved.
avert the possibility that something just mentioned (if bad) might not occur,