Advanced Shell Programming

EXPERIMENT NO. 10

Advanced Shell Programming

Objectives:

  1. To enhance programming skills using advanced shell programming
  2. To create and execute programs with decision making capabilities.
  3. To explore how loops are used in shell programming

Overview

Overview

Just like in any programming language, shell programming is also equipped with decision making features. In such a case, you provide two alternative sets of commands, and the shell program executes the set of commands depending on a specified criteria.

if

Making Decisions with if

Making decisions has always been part of our daily lives. Solving the exercises in this manual or not is a decision that the students have to make if you want to facilitate the learning of the UNIX operating system.

Just like in any programming language, shell programming is also equipped with decision making features. In such a case, you provide two alternative sets of commands, and the shell program executes the set of commands depending on a specified criteria.

The if command allows the shell program to make a decision, that is by evaluating certain conditions within the program. The shell then executes the set of command where the condition evaluates to true and ignores the other set of command.

The Concept of Success and Failure

The decision making process of the UNIX operating system is based on the concept of success and failure. The decision depends on the individual commands. But, what is success and what is failure. Whenever a command completes its task without error, then the command is successful. On the other hand, when the command aborts and displays an error, then the command is a failure. For example, listing the permission of a file, when a file is not existent or printing to an unknown printer.

The Basic Format of the if Command

The simplest format of the if command is as follows:

  if
     One or more commands
  then
     One or more commands
  fi

Whenever the shell encounters the structure above, it executes all commands between the if and the then commands. The shell checks on the last of these commands. If the last command succeeds, then the shell executes the commands between the then and the fi; otherwise, the commands are ignored.

The fi, if backwards is the tag indicating the end of an if statement. If only a single command follows the if, it can be written on the same line as the if.

The exercise below shows how the if command is used in a program. Create the script called “if.sh”:

  echo "Input name of file: "
  read filename
  if
      ls -l $filename
  then
      echo "Hurray!!!.  $filename is available"
  fi

if

else

The else Clause

The else clause gives an alternative whenever the if command evaluates to false. The else is used as follows:

  if
      One or more commands
  then
     One or more commands
  else
     One or more commands
  fi

The commands between the if and the then are always executed.

  • If the last command is successful, then the set of commands between the then and the else is executed. However,
  • Otherwise, the set of commands between the else and the fi is executed.

Only one set of command is executed. It can never be both!

Modify the previous exercise to give a more informative result as follows:

  echo "Input name of file: "
  read filename
  if
      ls -l $filename
  then
      echo "Hurray!!!.  $filename is available"
  else
     echo "Sorry!!!.  $filename is not available"
  fi

ifelse

The output of program remains the same as without the clause when the ls command finds the file. However, if it doesn’t, the output will be different. The program displays additional message when the file is not found, as follows:
ifelseexe

test

Performing Tests with test

The test command enables you to evaluate for conditions other than success or failure. The command succeeds or fails based on whether a given condition is true or false.

Using File Tests

The test command can determine whether a specified file meets a desired criterion. It has the following form:

  test [option] filename

Commonly Used Options for the test Command

Option Action
-f Checks whether a file exists and is a regular file
-d Checks whether a file exists and is a directory
-r Checks whether a file exists and is readable
-w Checks whether a file exists and is writable
-x Checks whether a file exists and is executable
-s Checks whether a file exists and has a size greater than zero

Modify the previous exercise and use the test command to produce a better output:

  echo "Input name of file: "
  read filename
  if test -f $filename
  then
      echo "Hurray!!!.  $filename is available"
  else
     echo "Sorry!!!.  $filename is not available"
  fi

test
testexe

The program behaves similar to the previous program, if the file is available. It behaves differently, otherwise. There was no error message displayed, if the file is not found; rather, just the friendly message is display.

Alternative Format of test

The test command has an alternative format that doesn’t even use the word test. That is, by enclosing the condition in brackets, as follows:

  [ condition ]

As in,

  If [ -f $filename ] 

Please observe the spaces between the condition and the brackets.

Performing Variable Tests

Probably the most important use of for test is checking the value of a variable. This test falls in two classes: string tests and numeric tests.

  1. The format of the string tests is as follows:

test value operation value

where: value represents a string, or a variable that contains a string

operation can either be = (equality) or != (difference)

  1. The format of the numeric tests is as follows:

test value operation value

where: value represents a number or a variable that contains a number

The operation is one of the following

Operation Meaning
-eq Numbers are equal
-ne Numbers are not equal
-lt The first number is less than the second
-le The first number is less than or equal to the second
-gt The first number is greater than the second
-ge The first number is greater than or equal to the second

Loops

Using Programming Loops

Perhaps the most important ability of any programming language is performing repetitive tasks. People get bored and tired doing the same thing over and over again, but not the computers. They can perform repeated works with extreme efficiency and accuracy.

A loop is a generic computer term for an operation done repeatedly. There are two commands that enable you to repeat tasks: for and while.

for-loop

Looping with for

The for command repeatedly performs a set of commands on a list of items, which could be anything such as user names, file names, a list of students. The for command has this format:

  for variable
     in list
  do
     commands
  done

Alternatively, the for and in can be written on the same line as follows:

  for variable in list
  do
     commands
  done

The commands between the do and done will be performed as many times as there are items in the list. The first time that the commands are executed, the variable takes the value of the first item in the list; the second time, gets the value of the second item in the list, and so on until all the items in the list are assigned.

The exercise below lists the shell programs of a directory:

  echo "These are the shell scripts in my directory:"
  for filename in *.sh
  do
     echo "Name of file: $filename"
  done
  echo "That's all folks"

for
forexe

while

Looping with while

The shell’s other looping command is while, and uses the following format:

  while
     One or more commands
  do
     One or more commands
  done

The while loop resembles the if command. In fact, the while command works the same way as the if command. It executes all the commands between the while and the do statements, checking whether the last command succeeds or fails. If the last command succeeds, the commands between the do and the done statements will be executed; otherwise, if it fails, these commands are skipped and shell executes the commands following the done statement.

The exercise below demonstrates the use of the while command. It asks for the subject you enrolled, one per line. The program asks the same question repeatedly until you enter the word ‘exit’.

  echo "Please enter the subjects you enrolled this semester."
  echo "Enter 'exit' to exit the program"
  while
     echo "Subject : "
     read subject
     test $subject != "exit"
  do
     echo "You are enrolled in : $subject."
  done
  echo "Thanks for answering the question"
  echo "bye"

while

whileexe

Exercises

Exercises

  1. Some users are comfortable with the read command for input while others with command line parameters . Create a program that:
    1. Prompts the user “What is your last name?” if no command parameter is provided. Otherwise, consider the command-line parameter as the last name. Then,
    2. Display “Hello, Mr. <last name>!”.
  2. Create a shell script that copies every file in a directory to file with .bak suffix.
  3. Create a shell script that do the following:
    1. Asks for the last name
    2. Asks for the sex (assume: only letters M and F are entered)
    3. Displays a greeting
      1. If the sex is “M”, Hello Mr <last_name>!!!
      2. Otherwise, display Hello, Ms <last_name>!!!
  4. Create a shell script that do the following:
    1. Asks for a name of file, if the file doesn’t exist, ask again
    2. If the fie exists, display its permissions.

Technorati Tags: , , ,

You can leave a response, or trackback from your own site.

Leave a Reply

Powered by WordPress | Find BlackBerry Phones for Sale Online. | Thanks to Top Bank CD Rates, Free MMORPG Games and Home Information Packs