52
Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

  • View
    238

  • Download
    4

Embed Size (px)

Citation preview

Page 1: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

Chapter 15

Mr. Mohammad Smirat

SHELL PROGRAMMING(Bourne Shell)

Page 2: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

Running a Bourne Shell Script

There are three ways to run a bourne shell script. Make the script file executable by adding execute

permission to the existing access permissions for the file. (on Bourne shell)

$chmod u+x script_fileThen type the script_file name as a command to execute the shell script, the shell is executed by a child of the current shell.

Execute the shell script by running the /bin/sh command.

$ /bin/sh script_file or$ sh script_file

Page 3: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

Running a Bourne Shell Script

Force the current shell to execute a script in the Bourne shell, regardless of your current shell. You can do so by starting you shell script with:

#!/bin/shall you need to do is set execute permission for the script file and run the file as a command. When the current shell encounter #!, it takes the rest of the line as the absolute pathname for the shell to be executed.

Page 4: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

Shell Variables

A variable is a main memory location that is given a name, which allow you to reference the memory location by using its name instead of its address. (the name is composed of digits and letters).

Shell environment variables, used to customize the environment in which your shell runs and for proper execution of shell commands.

A copy of these variable is passed to every command that executes in the shell as its child.

They are initialize at login time, when .profile or .login executes, then you can customize these by changing your .profile or .login files.

Page 5: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

Shell Variables

Some of the environment variables are writable, you can assign any values to them, other variables are read only, which means that you can not change them, only you can use them, examples of the read only (command line arguments) are $0, $! And others in table 15.2 page 398.

User defined variables, which used within shell scripts as temporary storage places whose values can be changed when the program executes. They can be made as read only variables. You do not have to declare and initialize shell variable, they are initialized to null string by default.

Page 6: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

Displaying shell variables

You can display the values of all shell variables (including user defines ones) and their values by using the set command without any parameters.

$setPS1=‘$ ‘PS2=‘> ’

We can use the env (in V system and printenv in BSD) command to display environments variable, and this will display all variable but not the user defined ones.

Page 7: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

Reading and Writing shell variables

We can use the assignment statement variable1=value1[varaible2=value2………]to assign values to the shell variable.

Note there is no space before and after the equal (=) sign.

When you want to read the variable you need to insert (prefix) the variable with $.

$ name=John$echo $namejohn

Page 8: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

Reading and Writing shell variables

$name=John DoeDoe : not found

$echo $name

$name = “John Doe”$echo $nameJohn Doe$echo \$name$name$ echo ‘$name’$name

$ echo “$name”

John Doe

Page 9: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

Reading and Writing shell variables

If the value of the variable is a valid command the expected result will be produces from that command, otherwise an error message will be issued.

$command=pwd$ $command/users/faculty/…….$command=hello$ $commandsh: hello command not found

Page 10: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

Command substitution

`command` substitute its output for ‘command’

$ command=pwd$ echo The command is: $command.”The command is: pwd.$command=`pwd`$ echo “the command is: $command.”The command is: /users/faculty……….

The command substitution can be specified in any command.$ echo “The date and time is `date`.”The date and time is wed may 7 14:23:12…..

Page 11: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

Exporting Environment

When a variable is created, it is not automatically known to subsequent shells, the export command passes the value of a variable to subsequent shells or script. All read/write shell environment variables are available to every command, script, and sub-shell, so they are exported at the time they are initialized.

Export[name-list] To export the names and copies of the current

values in ‘name-list’ to every command executed from this point on.

$ name=john$ export name

Page 12: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

Exporting Environment

$cat display_nameecho $nameexit 0$ name=john$ display_namenothing

Note the script display_name displays a null string even though we init the name variable just before executing the script, because the name variable is not exported.

Page 13: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

Exporting Environment

What about the exit command? It is used to transfer control to the calling process in the preceding session.

The only argument of the exit command is an integer number which return the status to the calling process.

All UNIX commands return an exit status of 0 upon success and nonzero upon failure.

The return value of a command is stored in the read-only environment variable $?.

Page 14: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

Exporting Environment

$ name=John$ export name$ display_nameJohn$echo $?0

The session above creates an environment variable, exports it, then call script display_name, and finally print the value of return status of the display_name script which it is 0.

Page 15: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

Exporting Environment $cat export_demo

#!/bin/shname=“john Doe”export namedisplay_change_namedisplay_name exit 0

$cat display_change_name#!/bin/shecho $namename=“plain Jane”echo $nameexit 0

If we try to run the script export_demo we’ll get the following output:$export_demoJohn DoePlain JaneJohn Doe

Page 16: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

Resetting Variable

A variable retains its value as long as the script in which it is initialized executes.

You can reset the value of variable to null by either explicitly initialized it to null or by using the unset command.

unset [name-list] Which reset or remove the variable or

function corresponding to the names in “name-list”, where name-list is a list of names separated by spaces.

Page 17: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

Resetting Variable

$name=John place=JUST$echo “$name $place”John JUST$unset name$echo “$name $place” JUST$place=$echo “$name $place” (null- print nothing)

Page 18: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

Read Only User defined Variables

Whenever you need to use constants, it is a good programming practice to use a symbolic constants.

A symbolic constant can be created in the bourne shell by initialize a variable with the desired value and making it read-only by using the readonly command.

Readonly [name-list]

$name=Jim$place=Jordan$readonly name placeecho “$name $place”Jim Jordanname=John

Page 19: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

Read Only User defined Variables

When readonly command is executed without arguments, it displays all read-only variables and their values.$readonlyLOGNAME=cis22name=jimplace=Jordan$

Page 20: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

Reading from Standard Input

read variable-listread one line from standard input and assign words in the line to variables in “name-list”.

A line is read in the form of words separated by white spaces (<spaces> or <tab>) characters. The words are assigned to the variables in the order of their occurrence, from left to right.

If the number of words in the line is greater than the number of variables in ‘variable-list’, the last is assigned the extra words.

If the number of words is less than the number of variables, the remaining variables are reset to null.

Page 21: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

Reading from Standard Input

$cat read_demo#!/bin/shecho “enter input: \c”read lineecho “you entered: $line”echo “enter another line: \c”read word1 word2 word3echo “the first word is: $word1”echo “the second word is: $word2”echo “the rest of the line is: $word3”exit 0

Page 22: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

Reading from Standard Input

The following is the output when we run the script read_demo:

$ read_demoenter input: ABC one two threeyou entered: ABC one two threeEnter another line: ABC one two threeThe first word is: ABCThe second word is: oneThe rest of the line is: two three$

Page 23: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

Special Characters for the Echo Command \c prints line without moving cursor

to next line \n newline \r carriage control \t horizontal tab \v vertical tab

Page 24: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

Passing Arguments to Shell scripts

We can pass command line arguments to shell script,.

The values of the first nine arguments are stored in variable $1 through $9 respectively.

The $# contains the total number of arguments passed in an execution of a script.

The variables $* and $@ both contains the values of all of the arguments, but, $@ has each individual argument in quotes if it is used as “$@”.

The variable name $0 contains the name of the script.

Page 25: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

Passing Arguments to Shell scripts

$ cat demo1#!/bin/shecho “the command name is: $0echo “the number of command line args: $#.”echo “the value of the command line args: $1 $2 $3 $4 $5 $6 $7 $8 $9”echo “the values of the arguments are: $@.”echo “ another way is: $*.”exit 0

Page 26: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

Passing Arguments to Shell scripts

$ demo1 one two three fourthe command name is: demo1the number of command line args are: 4the value of the command line args : one two three fourthe value again: one two three fouranother way is : one two three four.

$ demo1 a b c d e f g h Ithe command name is: demo1the number of commands are: 9 The value of commands: a b c d e f g h Ithe value are : a b c d e f g h I another way is : a b c d e f g h I

Page 27: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

Shifting Arguments

Shift[n]to shift the command line arguments N positions to the left.

$cat shift_demo#!/bin/shecho “the first three args: $1 $2 $3”shiftecho “the args are: $@”echo “the first three args: $1 $2 $3”shift 2echo “the first three args: $1 $2 $3”echo “the args are: $@”exit0

Page 28: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

Shifting Arguments

$ shift_demo 1 2 3 4 5 6 7 8 9the first three args: 1 2 3the args are: 2 3 4 5 6 7 8 9the first three args: 2 3 4the args are: 4 5 6 7 8 9 the first three args: 4 5 6$

Page 29: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

Set Command

Set [argument-list]to set values of the positional arguments to the arguments in argument-list.

$datesun apr 10 12:34:33 EST 2002$ set `date`$echo “$@”sun apr 10 12:34:33 EST 2002$echo “$2 $3, $6”apr 10, 2002

Page 30: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

Set Command

$cat set_demo#!/bin/shfilename=“$1”set `ls -il $filename`inode=“$1”size=“$6”echo “Name\tInode\tSize”echoecho “$filename\t$inode\t$size”exit 0

Run the script with one parameter (sample), the file has the inode 23451 and size is 578 bytes.

$set_demo sampleName Inode Size

sample 23451 578

Page 31: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

Comments and program headers

Program header and comments help the maintenance people understand your program quickly. They help you understand your own code, specially if you try to read it after some period of time. Comments cost nothing in performance.

A comment line must start with the pound sign # as in the following, it does not have to start at new line it could start anywhere in line

# This is a comment line.

Page 32: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

Test command

Test [expression] or[[expression]]

the test command supports many operators for testing files and integers, testing and comparing strings, and logically connecting two or more expressions to form complex expressions. The test command has two different forms, which are synonyms for each other. Both forms are often used in shell scripts, so you should use the one you prefer.

$ if test $HOME or$ if [ $HOME ]

the brackets must be surrounded by white spaces.

Page 33: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

Operators for test command

-d file True if directory -f file True if file is ordinary -r file True if file is readable -s file True if file length is nonzero -t filedes True if file descriptor is associated with the

terminal. -w file True if file is writable -x file True if file is executable int1 -eq int2 true if equals int1 -ge int2 true if int1 GE int2 int1 -gt int2 true if int1 GT int2 int1 -le int2 true if int1 LE int2

Page 34: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

Operators for test command (cont…)

int1 -lt int2 true if int1 LT int2 str true if str is not empty str1=str1 true if both equals str1 != str2 true if not equals -n str true if length no zero -z str true if the length is zero

! Logical NOT -a Logical AND -o logical OR ( ‘expression’ ) parenthesis for grouping

expressions; one space before and one after.

Page 35: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

Program Control Flow Commands (IF STATEMENT) if-then-elif-else-fi statement:

if expression then

[elif expressionthen command-list][else command-list]

fi if expression

then commands

fi

Page 36: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

Program Control Flow Commands (IF STATEMENT)

The following script will return error message if the script is run with no or more than one command line argument or if the argument is not an ordinary file.

$cat demo2#!/bin/shif test $# -eq 0

thenecho “usage: $0 ordinary_file” exit 1fiif test $# -gt 1 then echo “usage: $0 ordinary file” exit 1fiif test -f “$1” then filename=“$1”set `ls -il $filename`inode=“$1”size=“$6”echo “name\tInode\tSize”

Page 37: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

Example (cont…)

echo echo “$filename\t$inode\t$size” exit 0fi echo “$0: arg must be an ordinary file”exit 1

Run samples are $ demo2usage: demo2 ordinary file ( no arguments)$ demo2 dir1demo2: arg must be an ordinary file $ demo2 sampleName Inode Sizesample 43533 578

Page 38: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

Example (if then elsif else fi)

$cat demo3#!/bin/shif [ $# -eq 0] then echo “usage: $0 file” exit 1 elif [ $# -gt 1] then echo “usage; $0 file” exit 1 fi

Page 39: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

Example (if then elsif else fi) (cont…)

if [ -f “$1”] then filename=“$1” set `ls -il $filename` inode=“$1” size=“$6” echo “name\tInode\tSize” echo echo “filename\t$inode\tSsize” exit 0 elif [ -d “$1”] thennfiles=`ls ”$1” | wc –w` echo “the number of files in the directory is $nfiles” exit 0else echo “$0: argument must be an ordinary file” exit 1fi

Page 40: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

Example (if then elsif else fi) (cont…)

Run samples

$ demo3 file1file1: not found in the pwd.$ demo2 dir1the number of file in the directory is 4demo2 sampleName Inode Sizesample 43533 578$

Page 41: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

The for statement

for variable [in argument-list]do command-listdone

Example :$cat for_demo1#!/bin/shfor places in Amman Damascus Beirut Cairodo echo “$places”doneexit 0

Page 42: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

For Example (cont…)

Sample run

$for_demo1AmmanDamascusBeirutCairo$

Page 43: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

For Example

$ cat user_info#!/bin/shfor userdo echo “$user:\t\c” grep `echo “$user”` /etc/passwd | cut -f5 -d:doneexit 0$user_info cis1 cis4 cis5cis1: Mohamad cis4: Alicis5 Nabeel$

Page 44: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

The While Statement

while expressiondo command-listdone

To execute commands in command list so long as expression evaluates to true.

Page 45: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

While example

Write a program using while statement to enter your guesses for a secret code: init a secret code at the beginning of your

program. have a while loop to keep entering you

guesses and match the guesses to the secret code

display a message of failure if the guess does not match the secret code.

display a successful message when the guess match the secret code and exit the program.

Page 46: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

While Example (cont…)

$ cat while_demo#!/bin/shsecretcode=a007echo “Guess the code!”echo “Enter you guess: \c”read yourguesswhile[ “$secretcode” != “$yourguess”]do echo “Good guess but wrong. Try again!” echo “Enter you guess: \c” read yourguessdoneecho “wow! You are a genius!!!”exit 0

Page 47: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

While Example (cont…)

Sample run

$While_dempGuess the code!Enter your guess: abc123Good guess but wrong. Try again!Enter your guess: a0007Good guess but wrong. Try again!Enter your guess: a007Wow! You are genius!!!$

Page 48: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

The Until Statement

until expression do command-listdone

The opposite of while.

Page 49: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

break and continue

Same as C++. Break will end the loop and continue

execution at the first statement after it. Continue will end this iteration and continue

execution of the next iteration.

Page 50: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

The case Statement

case test-string in pattern1) command-list1 ;; pattern2) command-list2 ;; .. .. patternN) command-listN ;; *) any other pattern esac

Page 51: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

The case Statement Example Cat case_demo

#!/bin/shecho “use one of the following options:”echo “ d: To display date”echo “ l: To see the listing of files”echo “ q: To quit the program”echo “Enter you option and press enter: \c”read optioncase “$option” in

d) date ;;

l) ls;;

q) exit 0;;

*) echo “Invalid choice”exit 1;;

esac exit 0

Page 52: Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)

The case Statement Example (cont…)

$case_demoUse one of the following options:” d: To display date l: To see the listing of files q: To quit the programEnter you option and press enter: dwed May 15 12:34:44 EST 2002