Effective Use Of For Loop in Bash Shell Scripting

"for loops" are effective than "while loop" when a loop is to be done for each element in a array or each word in a string. This "for loop" is different, more powerful and useful then the version of for loop available in c/c .

Here i am here to show some interesting new ways to use them in our bash scripts.

Example 1: Simple and basic

data="Bash scripting is fun"
for i in $data
do
    echo "$i"
done

Output:

Bash
scripting
is
fun

Explanation:
    The bash [ Interpretor of the script ] splits each word in the variable data and each split piece is stored in the variable i on each iteration. The for loop starts and ends with 'do' and 'done' respectively.

Example 2: simple and direct


for i in Bash scripting is fun
do
    echo "$i"
done

Output:

Bash
scripting
is
fun

Explanation:
    Same as before but instead of using variable, we directly used data in the for loop.

Example 3 : simple and using doubt quotes

for i in "Bash scripting" "is fun"
do
    echo "$i"
done

Output:

Bash scripting
is fun

Explanation:
    When we enclose the data inside a doubt quotes then the whole data will be considered as a word by the interpreter [Bash].


After seeing above the three example, one might get an idea about 'for loop'. But the above three example doesn't satisfies all the realtime requirements.  For example we might have a variable containing data, "Bash scripting is fun" in the first line and "and "i love it" in the next line and we want to fetch each line on each iteration then the first example cannot achieve it. We need use the ENVIRONMENTAL variable IFS. IFS is the GLOBAL variable which is used by the BASH to split the string into words.

Lets see with an example.

Example 4: Advance.

data="Bash scripting is fun
and i love it"

IFS=$"
"
for i in $data
do
    echo $i
done

unset IFS
 
Output:

Bash scripting is fun
and i love it

Explanation:
    I first set the IFS value as new line[that's why i entered "enter" ]. then same as example 1. Then finally unset IFS. That's it. It not only work for newline, if you want to split each word by the character ', ' then set the IFS as IFS=$",". Now the bash split the string by ','  into each word.

Comments

Popular posts from this blog

Can a Coroutine is useful without Asynchronous IO ?

Different way to search for files in Gnome