Why do different bacteria have different shapes? Is it only related to their function?
Reasons for Bacteria with different shapes as given in Wikipedia/Bacteria:
There is an article based on research by Kevin D. Young Bacterial morphology: Why have different shapes? which highlights 3 main points which defines the shape of Bacteria:
These factors play a role in shaping bacteria. Further he explains what in general gives the shape to bacteria:
Shape Matters: Why bacteria care how they look - This article highlights Kevin's work explaining why shapes matter for bacteria and they take it seriously for survival.
So adaptations to various environments could be possible but depending upon the environment we can not predict the shape of bacteria because some other factor might have played major role in giving shape to it. But the above mentioned 3 main factors gives some explanation.
As for how certain bacteria achieve their shapes, the cell wall plays an important role. Almost all bacteria have a cell wall made of a substance called peptidoglycan, a mesh of peptides and saccharides that provides rigidity and strength to the bacteria. This wall is produced through a complex series of steps that starts inside the cell, where the peptide and sugar units are attached to a lipid to make a compound called Lipid II. However, Lipid II must be flipped to the outer layer of the cell membrane to deliver the peptides and sugars to the growing cell wall. The proteins responsible for flipping the Lipid II are believed to be FtsW, RodA, and SpoVE. FtsW is considered the main enzyme for most cell growth. RodA is found in rod shaped bacteria and is considered necessary for cell elongation. SpoVE is used to build the thick cell walls of bacterial spores. By controlling how Lipid II is delivered to the growing cell wall, these proteins play a role in controlling cell shape.