Cyberithub

15 Practical Bash For Loop Examples in Linux/Unix for Professionals

Advertisements

In this article, I will take you through 15 Practical Bash for loop Examples in Linux/Unix for Beginners. If you are using Bash Scripting in Linux from long time then you might be aware of bash for loop and its usages. So in this article I thought to explain some real world examples which will help you understand some of the use cases that you might encounter.

For Loop is used in Bash Scripting to run the same piece of code multiple times. You can either run same piece of code in the same Server multiple times or same code multiple times in multiple Servers. It can be used either way depends on your requirement. We will understand more about its usages as we go through this article.

Bash For Loop Syntax

for varname in list;do command1;command2;done

or

for varname in list
do
  command1
  command2
  .........
done

or

for var in $(cat file1);do command1;command2;done

or

for var in $(cat file1)
do
  command1
  command2
  .........
done

or

for variable in server1 server2;do command1;command2;done

or

for variable in server1 server2
do
  command1
  command2
  .........
done

15 Practical Bash For Loop Examples in Linux/Unix for Professionals

Bash For Loop Examples in Linux/Unix

Also Read: How to Drop/Flush/Clear Cache Memory or RAM in Linux (RedHat/CentOS 7/8)

Example 1: How to Sync Time in multiple servers using Bash For Loop in Linux

If you want to sync time in multiple servers using bash for loop in Linux then you can use below loop. In this example, we have provided the IP of all Servers in server.txt and then going to every server using for loop and setting the time to 16:08:00 using date command as shown below.

[root@localhost ~]# for a in $(cat server.txt);do ssh root@$a date +%T -s "16:08:00";done

NOTE:

Please note that here I have already enabled passwordless authentication between Servers to avoid any password prompt. So do not be surprise if you run any of the commands given in this article and it ask you to provide the authentication password. To Know more about setting up Passwordless authentication, you can check Passwordless ssh login using ssh keygen in 6 Easy Steps.

Example 2: How to Check next 5 CPU Load Average using Bash For Loop in Linux

If you want to check next 5 CPU Load Average using bash for loop in Linux then you need to loop through each of the sequence from 1 to 5 and display the load average using cat /proc/loadavg for every sequence as shown below.

[root@localhost ~]# for i in $(seq 5);do cat /proc/loadavg;sleep 3;done
0.00 0.01 0.05 2/141 25158
0.00 0.01 0.05 2/141 25160
0.00 0.01 0.05 2/141 25162
0.00 0.01 0.05 2/141 25164
0.00 0.01 0.05 2/141 25166

Example 3: How to check the processes using maximum swap memory in Linux

If you want to check the processes using maximum swap memory in linux then you can use below bash for loop. In this example, we are using awk and sort tool with bash for loop to check the processes using swap memory as shown below.

[root@localhost ~]# for file in /proc/*/status ; do awk '/VmSwap|Name/{printf $2 " " $3}END{ print ""}' $file; done | sort -k 2 -n -r | less
xprtiod
xfs-reclaim/sda
xfs-reclaim/dm-
xfs_mru_cache
xfs-log/sda1
xfs-log/dm-0
xfs-eofblocks/s
xfs-eofblocks/d
xfs-data/sda1
xfs-data/dm-0
xfs-conv/sda1
xfs-conv/dm-0
xfs-cil/sda1
xfs-cil/dm-0
xfs-buf/sda1
xfs-buf/dm-0
xfsalloc
xfsaild/sda1
xfsaild/dm-0
writeback
watchdogd
watchdog/0
vsftpd 0 kB
tuned 0 kB
ttm_swap
systemd-udevd 0 kB
systemd-logind 0 kB
systemd-journal 0 kB
systemd 0 kB
sshd 0 kB
sshd 0 kB
sort 0 kB
sleep 0 kB
scsi_tmf_4
scsi_tmf_3
scsi_tmf_2

Example 4: How to convert all rows into columns based on Colon(:) separator

You can also use bash for loop to convert all rows into columns based on Colon Separator(:) as shown below. In this example, we are creating a file testfile.txt and converting its rows to columns using cut and paste command with for loop. Firstly we need to create a file testfile.txt using vi testfile.txt command.

[root@localhost ~]# vi testfile.txt
Hi:you:there
This:is:CYBERITHUB
hello:world:example

Then we need to run below bash for loop from i=1 to i<=3 to convert the rows into columns.

[root@localhost ~]# for ((i=1;i<=3;i++)); do cut -d: -f "$i" testfile.txt | paste -sd: ; done | column -t -s:
Hi      This     hello
you      is      world
there CYBERITHUB example

Example 5: How to convert all rows into columns based on Comma(,) field separator

Like above example, you can also use bash for loop to convert all rows into columns based on Comma(,) as shown below. In this example, we are creating a file testfile.txt and converting its rows to columns using cut, column and paste command with bash for loop as specified below. First let's create the file testfile.txt using vi editor.

[root@localhost ~]# vi testfile.txt
Hi,you,there
This,is,CYBERITHUB
hello,world,example

Then we need to run below bash for loop from i=1 to i<=3 to convert the rows into columns.

[root@localhost ~]# for ((i=1;i<=3;i++)); do cut -d, -f "$i" testfile.txt | paste -sd, ; done | column -t -s,
Hi       This     hello
you       is      world
there CYBERITHUB example

Example 6: How to Check the OS Version of Multiple Servers using bash for loop in Linux

If you want to check the OS Version of multiple servers using bash for loop in one line then you need to run below command. In this example, we are looping through 14.188.134.26 and 14.188.21.242 servers and running cat /etc/redhat-release command in each Server as specified below.

[root@localhost ~]# for i in 14.188.134.26 14.188.21.242;do echo ********OS Version of $i********;cat /etc/redhat-release;done
********OS Version of 14.188.134.26********
CentOS Linux release 7.8.2003 (Core)
********OS Version of 14.188.21.242********
CentOS Linux release 7.8.2003 (Core)

Example 7: How to Check the Memory Stats using bash for loop in Linux

If you want to check the memory stats of multiple servers in one line then you can use below bash for loop. In this example we are checking the memory stats of Servers 14.188.134.26 and 14.188.21.242 by looping through each of the server and running free -g command as shown below.

[root@localhost ~]# for i in 14.188.134.26 14.188.21.242;do echo ********Memory Stats of $i********;free -g;done
********Memory Stats of 14.188.134.26********
     total used free shared buff/cache available
Mem:  31    20    5     0       4         9
Swap: 0      0    0
********Memory Stats of 14.188.21.242********
     total used  free shared buff/cache available
Mem:  31    20    5      0       4         9
Swap:  0     0    0

Example 8: How to Find the Private IP of AWS EC2 Instance using bash for loop

If you want to find the Private IP of AWS EC2 instance then you can use below bash for loop. In this example, we are looping through each of the AWS EC2 instance using their public IP and checking the ip of interface eth0 to find the private IP using ip addr sh | grep -i eth0 | grep -i inet command.

[root@localhost ~]# for i in 14.188.134.26 14.188.21.242;do echo ********Private IP of $i********;ip addr sh | grep -i eth0 | grep -i inet;done
********Private IP of 14.188.134.26********
inet 172.31.14.87/20 brd 172.31.15.255 scope global dynamic eth0
********Private IP of 14.188.21.242********
inet 172.31.14.87/20 brd 172.31.15.255 scope global dynamic eth0

Example 9: How to Create a File in Multiple Servers using Bash For Loop in Linux

You can create a file in multiple servers using bash for loop in a single line as shown below. In this example, we are creating a file test.txt in server1 and server2 by looping through each server and running touch test.txt command as specified below.

[root@localhost ~]# for i in server1 server2;do ssh -q $i "touch test.txt;sleep 2";done

Example 10: How to start an application in multiple Linux Servers

If you want to start an application in a bunch of servers without manually login to each servers then you can use below bash for loop. In this example, we are starting an application /opt/app/start.sh > /dev/null in server1 and server2 and then checking the status using /opt/app/status.sh as shown below.

[root@localhost ~]# for i in server1 server2;do ssh -q *****$i*****;ssh -q $i "/opt/app/start.sh > /dev/null;echo "App is starting...";sleep 60;/opt/app/status.sh";done

Example 11: How to check disk space of multiple Linux Servers

If you want to check the disk space is multiple Linux servers then you can use below bash for loop. In this example we are looping through all the servers of Servers.list and checking the disk space of /opt/backup and /opt/log using df -h /opt/backup /opt/log command.

[root@localhost ~]# for i in $(cat Servers.list);do ssh $i 'df -h /opt/backup /opt/log';done

Example 12: How to Check Kernel Version of Multiple Linux Servers

If you want to check the Kernel Version of Multiple Linux Servers then you need to use below for loop. In this example we are checking the Kernel version of 14.188.134.26 and 14.188.21.242 servers using uname -r command with for loop as shown below.

[root@localhost ~]# for i in 14.188.134.26 14.188.21.242;do echo ********Kernel Version of $i********;uname -r;done
********Kernel Version of 14.188.134.26********
3.10.0-1127.18.2.el7.x86_64
********Kernel Version of 14.188.21.242********
3.10.0-1127.18.2.el7.x86_64

Example 13: How to Find the total number of CPUs in Multiple Servers using bash for loop in Linux

If you want to find the total number of CPU cores in multiple servers then you can use below bash for loop. In this example, we are looping through Server 14.188.134.26.54 and 14.188.21.242 and running lscpu command in each of the server to find the total number of cores.

[root@localhost ~]# for i in 14.188.134.26 14.188.21.242;do echo ********Number of CPUs in $i********;lscpu | grep -v list | grep -v NUMA | grep -i "CPU(s)";done
********Number of CPUs in 14.188.134.26********
CPU(s): 8
********Number of CPUs in 14.188.21.242********
CPU(s): 8

Example 14: How to Check SELinux Status in Multiple Servers using bash for loop in Linux

You can also use bash for loop to check the SELinux status in multiple servers. In this example we are checking the status of selinux by looping through 14.188.134.26 and 14.188.21.242 servers and running sestatus command as shown below.

[root@localhost ~]# for i in 14.188.134.26 14.188.21.242;do echo ********SELinux Status in $i********;sestatus;done
********SELinux Status in 14.188.134.26********
SELinux status: enabled
SELinuxfs mount: /sys/fs/selinux
SELinux root directory: /etc/selinux
Loaded policy name: targeted
Current mode: enforcing
Mode from config file: enforcing
Policy MLS status: enabled
Policy deny_unknown status: allowed
Max kernel policy version: 31
********SELinux Status in 14.188.21.242********
SELinux status: enabled
SELinuxfs mount: /sys/fs/selinux
SELinux root directory: /etc/selinux
Loaded policy name: targeted
Current mode: enforcing
Mode from config file: enforcing
Policy MLS status: enabled
Policy deny_unknown status: allowed
Max kernel policy version: 31

Example 15: How to Check the Service Status in Multiple Servers using bash for loop in Linux

You can also use bash for loop to check the service status in multiple servers. In this example we are checking the status of iptables service by looping through 14.188.134.26 and 14.188.21.242 servers and running systemctl  status iptables command as shown below.

[root@localhost ~]# for i in 14.188.134.26 14.188.21.242;do echo ********IPTABLES Status in $i********;systemctl status iptables;done
********IPTABLES Status in 14.188.134.26********
● iptables.service - IPv4 firewall with iptables
Loaded: loaded (/usr/lib/systemd/system/iptables.service; enabled; vendor preset: disabled)
Active: active (exited) since Sat 2020-09-05 20:38:20 UTC; 1h 0min ago
Process: 612 ExecStart=/usr/libexec/iptables/iptables.init start (code=exited, status=0/SUCCESS)
Main PID: 612 (code=exited, status=0/SUCCESS)
Tasks: 0
Memory: 0B
CGroup: /system.slice/iptables.service

Sep 05 20:38:20 ip-172-31-14-87.us-west-2.compute.internal systemd[1]: Starting IPv4 firewall with iptables...
Sep 05 20:38:20 ip-172-31-14-87.us-west-2.compute.internal iptables.init[612]: iptables: Applying firewall rules: [ OK ]
Sep 05 20:38:20 ip-172-31-14-87.us-west-2.compute.internal iptables.init[612]: touch: cannot touch ‘/var/lock/subsys/iptables’: No such file or directory
Sep 05 20:38:20 ip-172-31-14-87.us-west-2.compute.internal systemd[1]: Started IPv4 firewall with iptables.
********IPTABLES Status in 14.188.21.242********
● iptables.service - IPv4 firewall with iptables
Loaded: loaded (/usr/lib/systemd/system/iptables.service; enabled; vendor preset: disabled)
Active: active (exited) since Sat 2020-09-05 20:38:20 UTC; 1h 0min ago
Process: 612 ExecStart=/usr/libexec/iptables/iptables.init start (code=exited, status=0/SUCCESS)
Main PID: 612 (code=exited, status=0/SUCCESS)
Tasks: 0
Memory: 0B
CGroup: /system.slice/iptables.service

Sep 05 20:38:20 ip-172-31-14-87.us-west-2.compute.internal systemd[1]: Starting IPv4 firewall with iptables...
Sep 05 20:38:20 ip-172-31-14-87.us-west-2.compute.internal iptables.init[612]: iptables: Applying firewall rules: [ OK ]
Sep 05 20:38:20 ip-172-31-14-87.us-west-2.compute.internal iptables.init[612]: touch: cannot touch ‘/var/lock/subsys/iptables’: No such file or directory
Sep 05 20:38:20 ip-172-31-14-87.us-west-2.compute.internal systemd[1]: Started IPv4 firewall with iptables.

 

 

 

 

Recommended Posts:-

10 Useful iproute2 tools examples to Manage Network Connections in Linux

6 Popular Methods to List All Running Services Under Systemd in Linux

Unix/Linux Find Files and Directories Owned By a Particular User(5 Useful Examples)

33 Practical Examples of ulimit command in Linux/Unix for Professionals

Install Node.js in 6 Easy Steps on Ubuntu 18.04

How to Install NVM for Node.js on Ubuntu 18.04

How to Limit CPU Limit of a Process Using CPULimit in Linux (RHEL/CentOS 7/8)

How to Install Rust Programming Language in Linux Using 6 Best Steps

Bash For Loop Examples to Check Processes using Swap Memory in Linux

Leave a Comment