We use cookies to improve our services and provide a better experience. By continuing to use this site, you agree with our Cookies Policy.

Tutorials
More than 400 step-by-step articles to guide you through online project development.
HomeTutorialsHosting ServicesCloud ServersAll Tutorials

How to Use (for) Loop in Linux Shell Console

cPanel KVM
Windows Cloud Server
Brazil VPS
Linux Cloud Server
Ubuntu VPS
USA VPS
Germany Cloud Servers
Linux KVM Hosting
KVM VPS
OpenVZ VPS

When it comes in doing multiple actions that requires repeat feature, we may use for loop directly in the shell console. The basic structure looks like this:

for i in `items in array`; do something with $i ; done

The first part for i in `items in array`reads item by item from array into variable i. The second part do something with $i performs particular action with variable $i. Once all items from array have been affected, loop ends with the command done.

To use this loop in the real example, we can try to find all processes by particular user and terminate them. To do this we will need to find such processes by using command ps aux | grep username. To find apache processes, replace username with apache. We should get something like this:

apache   19341  0.0  0.6 288332  6692 ?        S    13:42   0:00 /usr/sbin/httpd
apache   19342  0.0  0.6 288332  6692 ?        S    13:42   0:00 /usr/sbin/httpd
apache   19343  0.0  0.6 288332  6692 ?        S    13:42   0:00 /usr/sbin/httpd
apache   19344  0.0  0.6 288332  6692 ?        S    13:42   0:00 /usr/sbin/httpd
apache   19345  0.0  0.6 288332  6692 ?        S    13:42   0:00 /usr/sbin/httpd
apache   19346  0.0  0.6 288332  6692 ?        S    13:42   0:00 /usr/sbin/httpd
apache   19347  0.0  0.6 288332  6692 ?        S    13:42   0:00 /usr/sbin/httpd

From this output we can see that pid numbers are located in the second column. In this case, we can filter them by using awk filter. The full command should look as follows:

ps aux | grep apache | awk ‘{print $2}’

By executing the mentioned command we should get the following lines in the output:

19341
19342
19343
19344
19345
19346
19347

Now those pid numbers can be used as array in the for loop. In this case we can put command ps aux | grep apache | awk ‘{print $2}’ in for loop which should look as follows:

for i in `ps aux | grep apache | awk ‘{print $2}’`; do kill $i ; done

With the help of this command, we will list all pid numbers of apache processes and terminate them with command do kill $i.

Linux Cloud Server
Ubuntu VPS
USA VPS
Linux KVM Hosting
OpenVZ VPS
KVM VPS
cPanel KVM
Germany Cloud Servers
Windows Cloud Server
Brazil VPS
Rate this Tutorial:
No Comments Leave a Comment
Leave a Comment

Other (3)

Popular Keywords