I was wondering why soldiers facing off in previous wars stood so close to one another, without taking shelter? They basically lined up to get shot. The soldiers (or militia) that fled, were considered cowards, and deserters, and were shot anyway. Trench warfare was not "really" invented until WWI (I admit some Civil War battles did include digging in, but not most).
The building of field fortification is a time honoured tradition dating back to the Roman Legions at least. Yes, form has changed over the centuries as weapon technology has evolved. As you mentioned, trenches evolved during the ACW (1861-65) as the range and accuracy of gun powder weapons increased but you might be surprized to learn of the use of trenches a century earlier as forts were besieged. Search for "Vauban". Trenches were used to protect the side besieging a fort or a city as it easier and faster to dig underground rather than erect walls while under fire. In effect the Western Front of the Great War was a thousand-mile siege, from the sea to the Rhine, from 1914 to 1918.
Trenches have been around for a very long time. One of the first "modern" examples, as mentioned above, was during the closing years of the American Civil War. The First World War was conducted on a massive front, between industrialized nations that had widespread access to the equipment that favored such a defense. Not the least of which was the machine-gun and artillery. Smokeless powder rifles were in common use by the armies of that period too.
In the "dark ages" Europeans surrounded castles with trenches, before that Caesar used trenches around palisades. Caesar had his trenches defended with spears embedded in the ground, by the time of WWI we had rifles with bayonets embedded in people, commonly referred to as "cannon fodder".