[ This is a five part series that covers the very basics of Linux shell scripting. For the very beginning, start from Part I here.]
In the previous part, we had seen how to use system as well as user defined variables in shell scripts. This part will cover something really really cool and useful by discussing loops.You will see how useful they can be when used.
Loops do what they mean. Check for some condition and execute some stuff as defined. The simplest and pretty useful loop used in shell scripts is the if-then-else loop. There are various other loops too like while, for, until but for simplicity the most common loops of if-then and for are described here.
If then loop :
Here is how it works :
If some command / condition
do some commands as mentioned here
do these commands / conditions here
An example of script where if loop is used will make it more clear.
The output of this script is :
Let us change it to a fake command and see what message do we get :
Here is a cool script based on the loop discussed above :
The purpose of the above script is to check for a specific user name, if present it will list all the files of that specific user folder. This is done by using grep on /etc/passwd file.Here, the above script will list all contents of Pictures folder belonging to user named avp if the user exists.
The output for this script is :
Awesome isn’t it, few lines that can accomplish so much ?
for something in someone
An example will make it clear, plus you will see how handy can for be when used with previously described if-then loop :
Let’s make a script that will scan a specific directory path, then list the contents found within as being a file or a directory.
Over here, first the directory contents are read using the user variable : content in a for loop. Within the for loop, the if loop is used to test conditions -d or -f as value of variable content. -d will print the contents as directory and -f as files.
Output as below :
As you can see, how simple it is to make useful scripts when loops are used, this is the power of Linux shell in general. Each command does it’s job very very well and can be integrated within a script to achieve the desired result.
The last part will deal with how shell scripts can interact with users, followed by some cool scripts that can be used on daily basis.