0% found this document useful (0 votes)
129 views

Chapter 5: Unix Shell Programming

The document summarizes various control flow statements in Unix shell programming including for, while, until, if/then/else, case, and nested if statements. It provides examples of how to use each statement type and discusses generating values for loops, pattern matching in case statements, and checking file status.

Uploaded by

Mahesh Kumar
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
129 views

Chapter 5: Unix Shell Programming

The document summarizes various control flow statements in Unix shell programming including for, while, until, if/then/else, case, and nested if statements. It provides examples of how to use each statement type and discusses generating values for loops, pattern matching in case statements, and checking file status.

Uploaded by

Mahesh Kumar
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 13

CHAPTER 5 : UNIX SHELL PROGRAMMING

for loop: A loop is a programming device that lets you cycle through the same steps several times. The general form of the procure shell for loop is: for variable-name in value1 value2 ......... do ----statements---done Ex: for i in ACE ERA ACS do echo $i is in Hyderabad echo In Hyderabad $i \ ? echo " done Assume it is in an executable file comp then try running it. The i in the first line is the shell variable. The list of companies are the values that the variables assume in succession as the shell executes the for loop. The $i represents the current value of the variables i. A for loop can get values from the command line as in this case. for i in $1 $2 $3 do echo $i is in Hyderabad done Arguments for this shell script are passed from the command line during the execution as: $ sh comp ACE ACS ERA The same comp script can be changed by using $* which stands for all command line arguments following the script name: for i in $* do echo $i is in Hyderabad. echo In hyderabad $i echo in hyderabad $i done Generating values for a for loop: for loop variables get values in many ways some of them are discussed here under: " $i !

Unix Shell Programming 1. List the values explicitly after the "in" statement. for name in ACE ERA ACS 2. Take values from the command line for i in $* 3. Take filename from a directory as values for file in * 4. Take values from a shell variable using read read name for n in $name 5. Take values from the output of a command for i in `cat test` What output would the following program give? n=0 for i in $* do n=`expr $n + 1` echo Total number of arguments are $# echo All the arguments are $* echo Argument no. $n is $i done

5.1 The case Statement:


The Case Statement lets a shell script choose from a list of alternatives. The general form of the Case Statement is case value in 1) Commands;; 2) Commands;; esac Here the numbers 1 and 2 are labels that identify potential choices of action. If the value portion has the value of choice 1, then the commands following the choice 1 label are executed. The word esac marks the end of the case statement.

Unix Shell Programming Case Statement is used to set up menus. Eg: echo please enter the choice echo ' 1 date echo ' 3 ls read choice. case $choice in 1) date;; 2) who;; 3) ls;; 4) pwd;; *) echo that wasn't the required choice ! Bye esac We used the single quotes (') along with the echo to preserve the spacing. will print just one space between each argument. The double semicolon the following labels. The right parenthesis Otherwise echo (;;) separates one Put this 2 who ' 4 pwd '

choice from the next. The case statement tries to match the value of choice against one of ()) is used to identify label names. program in a script "ask" and make it an executable file. The words case and esac must come at the beginning of a command that is at the beginning of the line, or after a semicolon (;) or ampersand (&). The '*' choice matches any value.

5.2 Setting up Choice:


The bar symbol (|) is not a pipe but serves as an (or) operator. The or operator lets a user to attach more than one label to the same response.

5.2.1 Command line Arguments:


Another way of supplying a value to a case statement is by supplying values to the script containing the statement, through the command line. For example, consider the following script case $1 in ACE) echo A Company for Training & S/W;; ACS) echo A Company for Software development;; ERA) echo A Company for Software development;; *) esac Values can be supplied to this script by typing $ mycompany ACE echo These are not of the groups of ACE ERA & ACS

Unix Shell Programming Here each command line argument is matched against the list of choices.

5.2.2 Pattern Matching:


We can use the metacharacters *,?,and [] for pattern matching. For example case $1 in ACE) echo A Hyderabad based Training centre;; *) It is not an ACE ACS ERA group company;; [aeiou AEIOU])echo word beginning with a vowel;; ??) echo a two letter word esac Put this program in an executable file named "what" and execute it. What output would the following program give? for i in 0 1 2 3 do case $i in 0) echo number is $i I ate $i icecreams;; 1) echo number is $i I ate $i icecream;; 2) echo number is $i I ate $i icecreams;; 3) echo number is $3 I ate $i icecreams;; esac done

5.3 While and Until Statement:


Unix offers three loop structures for, while and until. The while and until structures depends upon the success or failure of a command. the general form is while control command do Commands done A while loop is executed depending on the status of the control command. For each cycle the shell attempts to execute the control command. If the command returns a zero exit status (success), the commands between do and done are executed. continues until the control command yields a non-zero exit status. This process

Unix Shell Programming Here is an example that watches for someone (say Raman) to login: While sleep 60 do who | grep Raman done. The sleep which pauses for 60 seconds will always execute normally (unless interrupted) and therefore return "success". Hence the loop will check once a minute to see if Raman has logged in. In this program if Raman has logged in you must wait 60 seconds. If raman stays logged in, you will be told about him once a minute, The loop can be turned inside out and written with an until, to provide the information once, without delay, if Raman is logged in currently, until who | grep raman do sleep 60 done In this case, the condition is first checked and if found to be true, the loop terminates, else the program waits for 60 secs. And the checking process is done. This cycle repeats until raman logs into the system. The until loop is similar to a while loop, with the difference that, it is executed until the test condition succeeds. In other words, a while loop runs until a control command fails, and the until loop runs until a control command succeeds. General form of Until Statement. until control command do Commands done Here the control command is executed, If it fails the commands between do and done are executed and the control command is attempted again. control command reports success. The process continues until the

Unix Shell Programming

5.4 The if Statement:


The "if statement in UNIX is used to test for conditions and execute the given steps if control command then ----Commands---fi If the command is successful (exit status is 0) then the command between the then and fi are executed. eg: The program, called clean, described below, compares two files and removes the second one if the files are identical. If cmp -s $1 $2 then rm $2 fi $ clean test test1 (Success or 0 if the files match, failure or 1 if they don't) is reported to the shell. The if----- then----- else statement: This helps the user to have an else option if control command then commands else commands fi To cite an example, type the following instructions into a file called clean1. if cmp -s $1 $2 then rm $2 echo the $2 file was a duplicate and has been removed. else echo the files $1 and $2 are not the same fi now run the program clean1 $ clean1 test test1 depending on the success or failure of the said conditions.

Unix Shell Programming If the given condition, "if cmp -s $1 $2", executes successfully, then the instructions between the then and else are executed. If they are different then the instructions between else and fi are executed. The if then ------- elif statement: A further extension to the if form, this lets you string several alternatives one after the other. The usage of elif keyword is similar to the else if statement. general form: if control command 1 then ----commands---elif control command 2 then ----commands---else ----commands---fi Let us take an example. Type the following text in a file called test.sh read salary if test $salary -ge 3000 then echo the grade is A elif test $salary -ge 2000 then echo the grade is B elif test $salary -ge 1500 then echo the grade is C else echo the grade is D fi In this case if the condition in the first "if succeeds, then all statements between then and elif are executed. If the condition fails the next if condition is evaluated and if this succeeds, the statements between then and elif are executed. If the entire if conditions fail then the statements between else and fi are executed.

Unix Shell Programming

5.5 The nested if statement


The nested if construct is used to check for dependent conditions. That is, a condition to be checked only on the success of a previous condition. Let us take an example. Type the following text in a file called test1.sh read a b c if test $a -gt $b then if test $a -gt $c then echo $a is the largest else echo $c is the largest fi else if test $b -gt $c then echo $b is the largest else echo $c is the largest fi fi This program prints out the largest among three givn numbers. If the first condition (if test $a -gt $b) fails, then, the statements specified after the else are executed. In this case, it is another conditional check. The condition "if test condition succeeds. $a -gt $c" is executed only if the first

5.6 File checking:


The test command is used to check the status of a file. -r file -w file -f file -d file -s file : : : : : True if the file exists and is readable. True if the file exists and is writable. True if the file exists and is not a directory. True if the file exists and is a directory. True if the file exists and has a size than 0. -x option is used for identifying an executable file. greater

Unix Shell Programming For example: $ echo sometext >rama $ if test -r rama > then > > > > fi The file called rama is a readable file $ The first instruction echoes a text into the file called Rama. The second instruction has checked whether the file called rama is a readable file or not and has reported with an affirmative. echo The file called rama is a readable file else echo The file called rama is not a readable file

5.7 File Descriptors :


Every program has three default files established when it starts, numbered by small integers called file descriptors the standard input, 0, the standard output, 1, the standard Error output 2. $ test -t tests if the standard output is being directed to terminal. $ test -t 0 tests if the standard output is $ test -t ; echo $? 0 $ test -t > save ; echo $? 1 In the first case the standard output was the terminal, so test returned the value 0. In the second case the standard output was directed to a file called save, so the standard output was not the terminal and hence it returned the exit status value of 1. Tests on numerical values: These test the relationship between two numbers . N <operator> M connected to your terminal. your

Unix Shell Programming the operators that can be used are - eg - ne - gt - lt - ge - le the values of N and M are equal The values of N and M are not equal N is greater than M N is less than M N is greter than or equal to M N is less than or equal to M

Let's take an example. $ users=`who | wc -l` $ if test $users -qt 8 > then echo "more than 8 people logged on" > fi The variable called users will store the value that is returned by the pipeline command, which is nothing but a number, indicating the number of users currently logged in. This is compared with 8 and if it is greater than this value, the message "more than 8 people logged on" is printed.

5.7.1 Logical operations:


Test command has options for logical operations they are: ! negates the following expression -a the and operator -o the or operator The -a stands for a logical 'and', the result of the test is true only if both expressions are true. The -o stands for logical 'or', the result of the test is true if either of the expressions is true. Let us take an example. Type the following text in a file called append.sh if test -w $2 -a -r $1 then cat $1 >> $2 else echo cannot append fi Execute this script by typing the following at the command prompt. $ append prog1 prog2 In this case, the "if" condition checks for two possibilities, that is, argument 2 is a writeable file and argument 1 is a readable file. The statement "cat $1 >> $2", is executed only if the

10

Unix Shell Programming outcome of both these possibilities is positive.test !-r space - True if the file called space is not a readable file.

11

Unix Shell Programming test -r space -a -w space - True if file called space is readable and writeable. Note: Spaces should be allowed between the various options. Also note that the 'and' and 'or' operators are used between the tests they link, not before or after them. eg: This can be used to check two files and append the contents. Open a file "append" and write the program. if test -w $2 -a -r $1 then cat $1 >> $2 else echo cannot append fi now give $ append programme1 Programme2

5.8 Parenthesis for Grouping:


We can use parenthesis for a group of expressions. Shell metacharacters used in these expressions must be masked and hence the (\) back slash is used. Test \(-r space -a -n space\) -o \(-r spick -a -w spick\) This returns true if the file called space is both readable and writable or if the file called spick is both readable and writable. metacharacters, ) and (. The backslash (\) is used here, to mask the

5.9 EXIT COMMAND:


The exit statement terminates the shell script and gives the script an exit status. An exit status of 0 indicates a success and a nonzero exit status, indicates a failure, normally the shell procedure terminates when the end of file is reached. If you want to terminate the script sooner than that, you must use an exit command.

5.10 Sleep and Beep Command:


The sleep command causes the program to pause for the no. Of seconds mentioned after it. Ex: sleep 60 causes the program to pause for 60 seconds. The CTRL G (^G) character, causes the system to exit with a beep sound.

12

Unix Shell Programming For example, type the following in a file called beep. sleep $1 echo ^G HI wake up ! ^G $ beep 60 & This will introduce a 60-second pause, and then the message "HI wake up!" will displayed, preceded and followed by a beep.

5.11 Expression Command:


The expression command helps us to carry out simple arithmetic. It takes an arithmetic expression (sum or a product) evaluates it, and outputs the results. The operators are: +, -, *,/, The operator * here needs some special handling. When using this symbol in an arithmetic expression, it has to be masked using the backslash (\) symbol. ex: $ echo `expr 15 \* 3` 45 $ echo `expr 25 % 4` 1 # here % is the modulus operator

Note:
1. The arguments including the arithmetic operator must be separated by blank space from one another. 2. We also need to mask the * operator with a back slash or quotes otherwise it is interpreted by the shell as a request for filename expansion. 3. Expression division is integer division and is truncated to the nearest integer. 4. The % is the module operator provided by the shell.

13

You might also like