How do minute changes in an organism, as a result of evolution, get carried over to next generation
As populations expand, generation by generation, they will inevitably
  run into limits on resources. Not all individuals in a population are
  exactly alike as some will have traits that give them an advantage in
  survival. A change in any aspect of the environment can suddenly turn
  what had been just another variation or variant into either an
  advantage or a disadvantage  If a selective pressure (i.e. change in
  the environment), acts against or upon the differences between the
  individuals in a population, you get natural selection, which, through
  time, can cause a population to evolve


http://rmitchellbioanthro.weebly.com/uploads/2/3/7/6/23767919/natselinanutshell.pdf

Evolution consists of two essential things:

Random mutagenesis (in this case a slight change that occurs in the DNA, that causes a slight change in the protein to show up)

The second stage of evolution is natural selection. After the mutagenesis event, nature rigorously selects for the mutation. If the mutation has a fitness cost to the organism, it gets removed (the organism doesn't survive). By removing all things that are more costly than beneficial, nature selects for the fittest.



Take the examples of beetels here (http://evolution.berkeley.edu/evolibrary/article/evo_25)

Very rarely does the external environment directly change the DNA code (you can argue about epigenetics, but that's a different can of worms). Changes in the environment usually dictate the survival of organisms with different traits. In fact what usually happens is a change in the DNA code occurs naturally due to mutagenesis and that change undergoes the rigours of natural selection.

So in you case what might have happened is (I am postulating here, I would recommend a literature search to verify this), your bacteria had a tubular structure that it used to inject toxins in other cells. Some bacteria (due to genetic variation in sexual reproduction) had mutations that allowed it to move this tubular structure. This allowed it to survive more efficiently, and hence reproduce more. Eventually this population of bacteria, slowly replaced the bacteria who had no locomotor control on their "tube", and hence one stage of natural selection has occurred. Now this happens again and again, till the efficiency of the locomotion is optimal.

Might I suggest you read this book ?

Bonner, John Tyler. The evolution of complexity by means of natural selection. Princeton University Press, 1988.