Loop of the year goes to "for" loops.
Situation 1
Someone says, "Cliff, we need to add user1 to the fans_of_dallas_cowgirls group on all the servers."
Situation 2
I need to scp all the files in a directory to all the switches in the system. The files have the switch hostname in the filename, but they're cased different and have the file type on the end.
In these situations an admin who isn't thinking in loops, would individually run the necessary commands to accomplish the goal over and over, and management kind of expects that (which I prefer). However, this isn't necessary at all.
Situation 1 breakdown
The command to add a user to a group, that I would use as root, is the command below.
# usermod -a -G fans_of_dallas_cowgirls user1
Of course if you only administer 3 or less servers, you could just run the command on all the servers. However, any more than that and you are increasing chances of mistakes and the time spent ssh-ing into each server. The best thing to do is to have a server do all this for you with a "for" loop. However, first we need to make an array of all the servers we need to run this command on.
Array
# servers=('server1' 'server2' 'server3' 'server4' 'server5' 'server6' 'server7')
Then we iterate the array with the for loop.
loop
# for server in ${servers[@]}; do ssh admin@$server usermod -a -G fans_of_dallas_cowgirls user1
While that's running you can go doom-scroll a social media site in the break room, and then come back and complain about how hard the task was.
Situation 2 breakdown
We were sent updates to the configuration in the switches but they're named like this.
OUR-Switch1_CFG.cfg
OUR-Switch2_CFG.cfg
OUR-Switch3_CFG.cfg
OUR-Switch4_CFG.cfg
OUR-Switch5_CFG.cfg
OUR-Switch6_CFG.cfg
OUR-Switch7_CFG.cfg
OUR-Switch8_CFG.cfg
OUR-Switch9_CFG.cfg
OUR-Switch10_CFG.cfg
The host name of switch1 is "our-switch1" and it all lower case for all the host names.
Before I could use bash properly this would be a lot of typing. Now all I have to do is the below commands.
First I assign the directory to a variable.
directory=/root/you/suck/at/bash/
I use the word count command to see how many characters are in the directory string. -n to avoid the new line character being counted
echo -n $directory | wc -m
Then I make a for loop that lower cases and extracts the hostname from the file name and uses the file name for the scp command.
for switch in $directory*; do base=${switch:23}; select=${base%_CFG.cfg}; lower={select,,}; scp $switch admin@$lower; done
These commands have saved me so much time. This is why it's crucial to be that guy that knows bash.
Comments