bash for loop examples
Contents
My favorite bash for loop examples.
server list from a file
Maybe you have bunch of servers and you need to check which ones are RHEL7 and which ones are still RHEL 6 (yikes !!)
#!/bin/bash
for SRV in $( cat server_list.txt ) do
ssh -q -i /home/sysadm/.ssh/my_rsa_id \
ec2-user@${SRV} "hostname; cat /etc/redhat-release;"
done
Maybe you have bunch of servers and you need to check if one package is installed or not and you need sudo
Here is the trick, use "" (double quotes) instead of '' (single quotes)
#!/bin/bash
for SRV in $( cat server_list.txt )
do
ssh -q ec2-user@${SRV} "hostname; sudo yum list installed | grep cloud-init"
done
open multiple ports with firewall-cmd
Maybe you have bunch of port numbers listed line by line inside data file and you need to add those ports to your iptables
#!/bin/bash
for PORT in $( cat data )
do
firewall-cmd --zone=public --add-port=${PORT}/tcp
firewall-cmd --zone=public --add-port=${PORT}/tcp --permanent
done
do something 10 times
Maybe you neeed a one liner.
for i in {1..10}; do echo ${i} ;done