Last time in “Scripting 101”, we introduced the concept of a bash shell script within the linux environment. A quick look at some basic constructs such as creating variables were examined. It was enough to get someone up and running but really didn’t have a whole lot of meat as far as doing anything complex. This time, in Scripting 201, we will examine some more complex ways of controlling the script execution such as querying the user for information, looping and using conditional statements.
Having the capability to run a script is great but if the script can’t query the user for information and must have hard coded information, the usefulness of the script will be severely limited. There are times when a script will want to know a path, what to name a file or folder, the default value for a variable and so on and so forth. This can be done in a very straight forward manner using read. Read will prompt the user to enter information. Before using read it is a good idea to first use echo to request what information is needed. That way the user knows what to enter. A simple example can be seen in Listing 1 where read is used to get the name of a folder that is being created by the script.
Listing 1 – Using Read to Prompt for Information
Just like in any standard computer program, controlling program flow within a script is important. There are a number of ways to do this using the familiar conditional statements such as if, for and while. While these are familiar, the actual implementation is slightly different than one would expect in C/C++. For example, an if is ended with an fi rather than simply being a single line or using brackets to conclude the statement. There are three different forms that the script form of if can take. They are similar to that in other languages. They include a single if, if else and if else if statements. The format can be seen in Listing 2.
Listing 2 – Forms of if
A good example to try is to check whether or not a user input is equal to a specified number. This would utilize the read function that we just talked about in addition to testing out the conditional statement. Listing 3 shows how this would be implemented.
Listing 3 – Checking a Users Input
There are also familiar looping structures such as the while loop. This conditional takes a similar form to if except that it using while[condition]; do instead of if[condition];then. An example can be found in Listing 4.
Listing 4 – Using a While Loop
While there are other looping and conditional statements used within bash scripting, these provide you with the basics. If you want to go a step further do a search for how you would create a for loop and also a do until loop. You will find that they follow a similar format to the if and while conditionals.