Advanced Bash Loops Tutorial

The BASH scripting language provides a very handy ‘loop’ features.  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.

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.


  • 23 Users Found This Useful
Was this answer helpful?

Related Articles

List files and directories using SSH

In order to list all files and directories using an SSH client, you would need to execute the...

Create/Edit files and folders using SSH cmd line

There are various ways you can create a new file using the SSH command line.The easiest and most...

Move and copy files using SSH

Often you will need to move one or more files/folders or copy them to a different location. You...

Deleting files and folders via SSH

Sometimes you would need to remove a file or a folder from the system. To do so using SSH, you...

Extracting and creating archive files via SSH

Sometimes you would need to extract or create an archive file (i.e to install a script, you would...