Advanced Bash Loops Tutorial
The BASH scripting language provides a very handy ‘loop’ features. In the previous tutorial page we have discussed that we can chain certain commands such as:
strace -p `pgrep -u root sshd`
This command however, provided that pgrep returns more than 1 process, will result in an error, since strace does not expect more than 1 process at a time. To overcome this issue, we can edit the line and add a loop control structure:
for i in `pgrep -u root sshd`; do strace -p $i ; done
What the above line will do is to create a for loop and for each result of pgrep to run strace -p.
Please note that you can not manipulate the system processes (executing ps, kill, pgrep, top and strace) on the shared server, since your account will not have such privileges. However, on our dedicated servers you will have root permissions and you will be able to control the system processes. Please check our dedicated servers offers for more details.
Another example would be to use the same for statement to remove a certain line in each file that contains it. Let’s imagine that you have hundreds of files containing a footer with copyright message with wrong year (i.e 1998 for example) and you need to remove it. The problem is the files are numerous and it will take a lot of time to do it by hand. Fortunately, you can use a single line in BASH to do it for you.
For the purpose, we will create a for loop, which will grep the whole directory and its subdirectories for the message we need to remove and pass it to a SED command which will actually process the file and remove it. The full command line will look like this:
for i in `grep * -r -l Copyrighted`; do sed '/Copyrighted/d' -i $i ; done
The line broken in parts is as follows:
1)for loop: for i in something; do something; done;
2)grep * -r -l Copyrighted -- greps the message and returns only the file names containing it
3)sed ‘/Copyrighted/d’ -i $i -- uses sed to remove the line from the files we have located with the above command.