Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Chapter 15 Mr. Mohammad Smirat SHELL PROGRAMMING (Bourne Shell)"— Presentation transcript:

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

2 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_file Then 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

3 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/sh all 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.

4 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.

5 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.

6 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. $set PS1=‘$ ‘ 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.

7 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 $name john

8 Reading and Writing shell variables $name=John Doe Doe : not found $echo $name $name = “John Doe” $echo $name John Doe $echo \$name $name $ echo ‘$name’ $name $ echo “$name” John Doe

9 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 $ $command sh: hello command not found

10 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…..

11 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

12 Exporting Environment $cat display_name echo $name exit 0 $ name=john $ display_name nothing 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.

13 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 $?.

14 Exporting Environment $ name=John $ export name $ display_name John $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.

15 Exporting Environment $cat export_demo #!/bin/sh name=“john Doe” export name display_change_name display_name exit 0 $cat display_change_name #!/bin/sh echo $name name=“plain Jane” echo $name exit 0 If we try to run the script export_demo we’ll get the following output: $export_demo John Doe Plain Jane John Doe

16 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.

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

18 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 place echo “$name $place” Jim Jordan name=John

19 Read Only User defined Variables When readonly command is executed without arguments, it displays all read-only variables and their values. $readonly LOGNAME=cis22 name=jim place=Jordan $

20 Reading from Standard Input read variable-list read 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 ( or ) 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.

21 Reading from Standard Input $cat read_demo #!/bin/sh echo “enter input: \c” read line echo “you entered: $line” echo “enter another line: \c” read word1 word2 word3 echo “the first word is: $word1” echo “the second word is: $word2” echo “the rest of the line is: $word3” exit 0

22 Reading from Standard Input The following is the output when we run the script read_demo: $ read_demo enter input: ABC one two three you entered: ABC one two three Enter another line: ABC one two three The first word is: ABC The second word is: one The rest of the line is: two three $

23 Special Characters for the Echo Command \cprints line without moving cursor to next line \nnewline \rcarriage control \thorizontal tab \vvertical tab

24 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.

25 Passing Arguments to Shell scripts $ cat demo1 #!/bin/sh echo “the command name is: $0 echo “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

26 Passing Arguments to Shell scripts $ demo1 one two three four the command name is: demo1 the number of command line args are: 4 the value of the command line args : one two three four the value again: one two three four another way is : one two three four. $ demo1 a b c d e f g h I the command name is: demo1 the number of commands are: 9 The value of commands: a b c d e f g h I the value are : a b c d e f g h I another way is : a b c d e f g h I

27 Shifting Arguments Shift[n] to shift the command line arguments N positions to the left. $cat shift_demo #!/bin/sh echo “the first three args: $1 $2 $3” shift echo “the args are: $@” echo “the first three args: $1 $2 $3” shift 2 echo “the first three args: $1 $2 $3” echo “the args are: $@” exit0

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

29 Set Command Set [argument-list] to set values of the positional arguments to the arguments in argument-list. $date sun 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

30 Set Command $cat set_demo #!/bin/sh filename=“$1” set `ls -il $filename` inode=“$1” size=“$6” echo “Name\tInode\tSize” echo echo “$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 sample NameInodeSize sample23451578

31 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.

32 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.

33 Operators for test command -d fileTrue if directory -f fileTrue if file is ordinary -r fileTrue if file is readable -s fileTrue if file length is nonzero -t filedesTrue if file descriptor is associated with the terminal. -w fileTrue if file is writable -x fileTrue if file is executable int1 -eq int2true if equals int1 -ge int2true if int1 GE int2 int1 -gt int2true if int1 GT int2 int1 -le int2true if int1 LE int2

34 Operators for test command (cont … ) int1 -lt int2true if int1 LT int2 strtrue if str is not empty str1=str1true if both equals str1 != str2true if not equals -n strtrue if length no zero -z strtrue if the length is zero !Logical NOT -aLogical AND -ological OR ( ‘expression’ )parenthesis for grouping expressions; one space before and one after.

35 Program Control Flow Commands (IF STATEMENT) if-then-elif-else-fi statement: if expression then [elif expression then command-list] [else command-list] fi if expression then commands fi

36 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/sh if test $# -eq 0 then echo “usage: $0 ordinary_file” exit 1 fi if test $# -gt 1 then echo “usage: $0 ordinary file” exit 1 fi if test -f “$1” then filename=“$1” set `ls -il $filename` inode=“$1” size=“$6” echo “name\tInode\tSize”

37 Example (cont … ) echo echo “$filename\t$inode\t$size” exit 0 fi echo “$0: arg must be an ordinary file” exit 1 Run samples are $ demo2 usage: demo2 ordinary file ( no arguments) $ demo2 dir1 demo2: arg must be an ordinary file $ demo2 sample NameInodeSize sample43533578

38 Example (if then elsif else fi) $cat demo3 #!/bin/sh if [ $# -eq 0] then echo “usage: $0 file” exit 1 elif [ $# -gt 1] then echo “usage; $0 file” exit 1 fi

39 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”] then nfiles=`ls ”$1” | wc –w` echo “the number of files in the directory is $nfiles” exit 0 else echo “$0: argument must be an ordinary file” exit 1 fi

40 Example (if then elsif else fi) (cont … ) Run samples $ demo3 file1 file1: not found in the pwd. $ demo2 dir1 the number of file in the directory is 4 demo2 sample NameInodeSize sample43533578 $

41 The for statement for variable [in argument-list] do command-list done Example : $cat for_demo1 #!/bin/sh for places in Amman Damascus Beirut Cairo do echo “$places” done exit 0

42 For Example (cont … ) Sample run $for_demo1 Amman Damascus Beirut Cairo $

43 For Example $ cat user_info #!/bin/sh for user do echo “$user:\t\c” grep `echo “$user”` /etc/passwd | cut -f5 -d: done exit 0 $user_info cis1 cis4 cis5 cis1:Mohamad cis4:Ali cis5Nabeel $

44 The While Statement while expression do command-list done To execute commands in command list so long as expression evaluates to true.

45 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.

46 While Example (cont … ) $ cat while_demo #!/bin/sh secretcode=a007 echo “Guess the code!” echo “Enter you guess: \c” read yourguess while[ “$secretcode” != “$yourguess”] do echo “Good guess but wrong. Try again!” echo “Enter you guess: \c” read yourguess done echo “wow! You are a genius!!!” exit 0

47 While Example (cont … ) Sample run $While_demp Guess the code! Enter your guess: abc123 Good guess but wrong. Try again! Enter your guess: a0007 Good guess but wrong. Try again! Enter your guess: a007 Wow! You are genius!!! $

48 The Until Statement until expression do command-list done The opposite of while.

49 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.

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

51 The case Statement Example Cat case_demo #!/bin/sh echo “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 option case “$option” in d)date ;; l)ls ;; q)exit 0 ;; *)echo “Invalid choice” exit 1 ;; esac exit 0

52 The case Statement Example (cont … ) $case_demo Use one of the following options:” d: To display date l:To see the listing of files q:To quit the program Enter you option and press enter: d wed May 15 12:34:44 EST 2002


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

Similar presentations


Ads by Google