The theory of evolution states that random variations in organisms occur to better suit their surroundings. We take for example a bacteria's flagella. There's a bacteria who has a tube kind of structure that it uses to inject toxins in other cells. Structure of flagella and this tubular structure is very similar. So biologists state that this is clear evidence for evolutionary process wherein this tubular structure underwent gradual changes that resulted into a flagella.
Now my question is, minute changes did occur to this tubular structure, but how do those changes get carried over to the next generation? Almost all components of a cell are created as per the instructions coded into DNA. So does it mean that every minute changes that occur to an organism get recorded into DNA so that they can be carried over? In above example, assume, that a few proteins got accidentally attached to the tubular structure that will help the structure to rotate. Now when this temporarily changed bacteria gets divided into a new one it will have lost that change. So to actually carry over this "beneficial" change would the bacteria have changed its genome? How does this happen? What is the basal mechanism that supports evolutionary changes?