0 penilaian0% menganggap dokumen ini bermanfaat (0 suara)
37 tayangan85 halaman
UNIX and Shell Scripting Module 6: Shell Programming 2 2 Module 6 Objectives Upon completing this course, the learner will be able to: - List different types of shells - Compare the advantages and disadvantages of different shells.
UNIX and Shell Scripting Module 6: Shell Programming 2 2 Module 6 Objectives Upon completing this course, the learner will be able to: - List different types of shells - Compare the advantages and disadvantages of different shells.
UNIX and Shell Scripting Module 6: Shell Programming 2 2 Module 6 Objectives Upon completing this course, the learner will be able to: - List different types of shells - Compare the advantages and disadvantages of different shells.
2 Module 6 Objectives Upon completing this course, the learner will be able to: List different types of shells Compare the advantages and disadvantages of different shells Describe Shell Script Explain the use of Shell Script Describe Interpreter Role Describe how to execute the Basic Shell Scripting Technique Describe how to execute flow control techniques in Shell Script Describe command line handling in Shell Scripts Explain the command line processing process Describe how to execute basic Shell Scripting debugging techniques
3
3 Module 6 Agenda Topic Name Duration Basic Shell Programming 140 min Flow Control 150 min Command Line Options and Processing 45 min Debugging 50 min
4
4 Discussion: Shell (1 of 2) Discussion topic: What is SHELL ? Have you used any shell or expect to use it?
Discussion time: 5 minutes
Instructions: Ask students about their experience/opinions. Write them on a flip-chart.
5
5 Shell (2 of 2) Translates user command lines into operating system instructions Acts as an interface (layer) between user and UNIX operating system Shell script is: A script or file that contains shell commands. Also called as shell program. Various operations performed by script include: File manipulation Program execution Printing text Operations (including App Startup, Shutdown, and Deployment)
6 Advantages of Shell Scripting Writing shell script is much quicker. Provides: Decision making (if/else, case statement) Linkage (call another script) Sequence (loops) Does not require compilation steps Generalizes sequence of operations Creates new commands using combinations of utilities Combines lengthy and repetitive sequence of commands into a single command Wraps programs
6
7 Disadvantages of Shell Scripting More prone to costly errors Slow in execution speed Generates new process for each execution
7
8 Typical Usage
8 User Usages System administrators To automate many aspects of: Maintenance Operations Application startup scripts Useful especially for unattended applications that start using cron or at commands. Application package installation tools Installation steps can be written in make files and be executed using make utility.
9
9 Types of Shell (1 of 4) Bourne Shell Is represented as sh Is an original shell of UNIX Is available on all UNIX systems as standard shell Does not provide interactive facility Permits shell script to be written and executed Was first to feature the convention of using file descriptor 2 > for error messages
Other innovations of Bourne Shell are: Here documents using << Command substitution using back quotes Support for environmental variables "for ~ do ~ done" loop
10
10 Types of Shell (2 of 4) Korn Shell Is represented as ksh Provides features of c shell Provides shell programming language similar to Bourne Shell Is the most efficient shell Is advised to be used as a default shell Provides the ability to edit the command line in WYSIWYG fashion What You See Is What You Get Implies a user interface Is a feature used to describe system in which content displayed during editing appears very similar to the final output
11
11 Types of Shell (3 of 4) Bourne Again Shell Is represented as bash Is widely used by the academic community Is a public domain shell Provides interactive features of c shell (csh) and Korn Shell (ksh) Is recommended as complete shell environment When bourne shell (sh) is used for shell programming Can be executed by bash without modification Is effective in integer calculations
12
12 Types of Shell (4 of 4) c Shell Is represented as csh Has its Syntaxes modeled after the c programming language Has typical UNIX shell structure Has many features and improvements added over the Bourne shell such as aliases and command history Interprets each line as a separate command Introduces following features for the first time Job control Array Aliases Math operations
13
13 Types of Shell Comparison Feature Shell Type sh csh ksh bash Job Control O P P P Command History O P P P Command Line Editing O O P P Local Variables O O P P Aliases O P P P Custom Prompt O O P P
14
14 Interpreter All Korn Shell scripts start with following line: #!/bin/ksh /bin/ksh is the name of Interpreter to be used, which can be different based on the type of shell in use: Say we write a shell script testScript. Save it in directory /usr/local. Pass arg1 and arg2 as arguments to it. To execute the script, write following on the prompt: /usr/local/testScript arg1 arg2 When the shell script gets executed, its command line arguments become: /bin/ksh /usr/local/testScript arg1 arg2
15 Demonstration Instructions There are demonstrations throughout this topic.
This topic comprises command sections for Basic Shell programming. These sections will be conducted in the following manner: Instructions: Explain the command with demonstration. Ask participants to execute the same. Discuss the related slide.
Note: The commands would be used by the faculty and participants simultaneously.
16
16 Role of Interpreter (1 of 2)
17
17 Role of Interpreter (2 of 2)
Result cat \File2 echo date Is; cat File2 echo Date
18
18 Wild Cards (1 of 6) Are the characters interpreted before any other action takes place Are used to find file and directory name Wild Card Description * Matches any number of characters in a filename, including none ? Matches any single character [] Set of characters, any one of which may match a single character at that position [!...] Set of Characters, which is not matched at that position
19
19 Wild Cards (2 of 6) Example Description [a-z] Matches all characters between a and z [!ab..z] Matches any character that does not appear within the brackets D*1 Matches all characters starting with D and ending at 1 ?[!abc]?- Matches any character as first letter Note: Character following the first letter should not be a,b,c; followed by any character in the end. [c-fmrv-z]* Matches first character as m or r; OR in the range of c to f, or v to z [!d-m]* Matches first character as anything other than the alphabet in the range d to m A?b? Matches four characters where first character is A and third character is b
20
20 Wild Cards (3 of 6) Example Description a[0-9] Matches a0, a1, and so on, up to a9 a[!0-9] Doesn't match a0, but matches aa [^ab..z] Matches any character that does not appear within the brackets, works for tcsh only a[^0-9] Doesn't match a0, but matches aa
21 Wild Cards (4 of 6)
21 Script Result Test Script
22 Wild Cards (5 of 6)
22 Script Result Test Script
23 Wild Cards (6 of 6)
23 Script Result Test Script
24
24 Preset Shell Variables (1 of 3) Are special variables used by the system Use uppercase names or punctuation characters Example: Login environment
Shell internal settings Variable Description $USER, $LOGNAME Preset to the currently login username. $PATH Lists the directories that will be searched for external commands. Variable Description $PWD Set the current working directory. $? Set to the exit status of the last command run.
25
25 Preset Shell Variables (2 of 3) Some of these variables are set by system and cant be modified. E.g., USER
Some can be modified. E.g., PATH
26
26 Preset Shell Variables (3 of 3)
Script Result Test Script
27
27 Setting, Exporting, and Using Shell Variable (1 of 2) Suppose we need to set environment to run an application, the application must have: Log file name as variable Log file path name as variable Library paths as variables Environment can be set by: Creating an Environment file Defining variables to hold the path/file names Assigning those variables to actual path/file names Exporting the path/file names so that main program can access it
28
28 Setting, Exporting, and Using Shell Variable (2 of 2) Syntax export variable=value We can have following in the environment file: export LOGFILENAME=LogFile.log; export LOGFILEPATH=/home/user1/prod/Logs; export LIBRARYPATH=/home/user1/prod/lib; execute application This will make the variables LOGFILENAME, LOGFILEPATH, and LIBRARYPATH available to the application which has been executed.
29
29 Positional Arguments (1 of 2) Convey information to a program Are variables defined by the shell Are nine in number $1 through $9 Example $ TestPosition Para1 Para2 Para3 $ echo $1
Additional Parameters: $# - Total number of arguments supplied to Shell $* / $@ - All positional parameters Note: $* is equivalent to $1 $2 . whereas $@ is equivalent to $1 $2
Assuming Name of the Script TestPosition List of Input Parameters Para1 Para2 Para3 Will Show the Result Para1, which is assigned to Positional Parameter $1
30
30 Positional Arguments (2 of 2)
Sample Output for Positional Parameters Sample Script for Positional Parameters
31
31 Command Substitution (1 of 2) Enables the connecting of two commands
Syntax $(command) Offered by Korn and Bash Shell
32
32 Command Substitution (2 of 2)
$date is substituted by date and time, the output of date command. ls F* command is substituted by the list of files starting with F.
33
33 I/O and Redirection (1 of 2) Following command is used for Display on the screen echo Display a line of text Redirection provides following features: Input from file in place of Keyboard (< Input Redirection) Output to file in place of Screen (> Output Redirection) Appending to a file by redirecting standard output (>> Redirection)
34
34 I/O and Redirection (2 of 2)
Display the message on the screen wc command is getting input from File2. Output of cat is appended to TestOutDirectFile. Output of ls is redirected to TestOutDirectFile.
35
35 File Attribute Checking (1 of 3) Checks the status of file Verifies specific status of file Variable Description -d file True if directory and exist -f file True if file and exist -s file True if size is greater than 0 and exist -r file True if has read permission and exist -w file True if has write permission and exist -x file True if has execute permission and exist -a file True if ASCII file and exist
36
36 File Attribute Checking (2 of 3)
Script for Ensuring Various File Attributes Result of Script Ensuring Various File Attributes
37
37 File Attribute Checking (3 of 3)
Result of Script Ensuring Various File Attributes Script for Ensuring Various File Attributes
38
38 String Operations (1 of 2) Checks for strings
String Operation Description = True if strings are same != True if strings are different -n True if length of string is greater than 0 -z True if the length of string is zero < True if string one is less than the two > True if string two is less than the one
39
39 String Operations (2 of 2)
Result of Script Ensuring Various String Operations Script for Ensuring Various String Operations
41 Arithmetic Operator (2 of 3) The expr command evaluates arithmetic expressions
Script for Relational Operations Result of Relational Operations
42
42 Arithmetic Operator (3 of 3) Script for Arithmetic Operations Result of Arithmetic Operations
43
43 Relational Operator (1 of 2) Operator Description > (-gt) Greater than < (-lt) Less than > = (-ge) Greater than or equal <= (-le) Less than or equal == (-eq) Equal to (comparison) != (-ne) Not equal to && (-a) And || (-o) Or
44
44 Relational Operator (2 of 2) Script for Relational Operations Result of Relational Operations
45
45 Test Command (1 of 2) Carries out several types of tests: Test Function Numerical Test Compares values of two numbers String Test Performs String Operations File Test Checks the status of a file
46
46 Test Command (2 of 2)
Result of Script Demonstrates Test Command
47
47 Activity 1: Command Line Script Activity time: 5 minutes The purpose of this activity is to use and understand the concept of positional or command line parameters to script.
Instructions: Write a shell script which will receive five numbers from command line and print the sum of those five numbers.
48
48 Activity 2: Reading File Activity time: 5 minutes The purpose of this activity is to read content of the file using script
Instructions: Write a shell script which would take input from a file and will print the number of lines, words, and characters in the file.
49
49 Activity 3: Command Line and Arithmetic Operations Activity time: 10 minutes The purpose of this activity is to understand the use of arithmetic operators in shell.
Instructions: Write a shell script which will receive two numbers from command line, perform the following Arithmetic Operations on those two numbers, and print the results. Addition Multiplication Modulus
50
50 Module 6 Agenda Topic Name Duration Basic Shell Programming 140 min Flow Control 150 min Command Line Options and Processing 45 min Debugging 50 min
51 Demonstration Instructions There are demonstrations throughout this topic.
This topic comprises command sections for Flow Control. These sections will be conducted in the following manner: Instructions: Explain the command with demonstration. Ask participants to execute the same. Discuss the related slide.
Note: The commands would be used by the faculty and participants simultaneously.
52
52 Usage of if-then-fi (1 of 2) Decision control structures if then fi Syntax if control command then Command(s) fi
Exit status of control command should be zero to execute then part. One or more commands/statements get executed, when control command is true.
53
53 Usage of if-then-fi (2 of 2)
Result Exit status of control command should be zero to execute then part.
54
54 Usage of if-then-else-fi (1 of 2) Decision control structures if then else fi Syntax if control command then Command(s) else Command(s) fi
55
55 Usage of if-then-else-fi (2 of 2) Decision control structures Result
56
56 Usage of if-then-elif-fi (1 of 2) Decision control structures if then - elif fi Syntax if control command then Command(s) elif then command(s) fi
else if can be replaced by elif
57
57 Usage of if-then-elif-fi (2 of 2) Decision control structures Result
58
58 Usage of while loop (1 of 2) Loop statements Involve repeating portion of the program while loop Executes a list of statements repeatedly while a certain condition holds true. Syntax while condition do command(s) done
Expression to terminate the loop
59
59 Usage of while loop (2 of 2)
Result
60
60 Usage of for loop (1 of 2) for loop Executes a list of statements a fixed number of times.
Syntax for variable in v1 v2 v3 v4 do command(s) done
Will work for list of values mentioned here Variable declaration not required
61
61 Usage of for loop (2 of 2)
Result
62
62 Usage of until loop (1 of 2) until loop Executes a list of statements repeatedly till condition remains false
Syntax until condition do command(s) done
Seeking for condition to become True to terminate the loop
63
63 Usage of until loop (2 of 2)
Result
64
64 Usage of Case Statement (1 of 2) Case statement control the sequence of execution Syntax case $value in choice1) do this ;; choice2) do this ;; *) do this ;; esac Labels for choice of action Valid UNIX command(s)
65
65 Usage of Case Statement (2 of 2)
Result
66
66 Define and Call a Function (1 of 2) Definition Function functionName() { # Body of The Function } or FunctionName() { # Body of The Function }
Call of Function Every function is called by name
67
67 Define and Call a Function (2 of 2)
Result
68
68 Activity 4: If Flow Control and String Operators Activity time: 10 minutes The purpose of this activity is to understand and learn the utilization of String Operators using if control statement.
Instructions: Write a shell script which would compare two strings and print appropriate message when: They are equal They are not equal Size is non-zero
69
69 Activity 5: While Flow Control Activity time: 5 minutes The purpose of this activity is to use and understand while loop working in shell script.
Instructions: Write a shell script which would print the series of first odd number from one to n, where n should be provided from command line.
70
70 Activity 6: Case Command Activity time: 5 minutes The purpose of this activity is to use and understand case command in UNIX shell.
Instructions: Write a shell script to provide number between one to nine from command line and print in words.
71
71 Module 6 Agenda Topic Name Duration Basic Shell Programming 140 min Flow Control 150 min Command Line Options and Processing 45 min Debugging 50 min
72 Demonstration Instructions For slides 75 and 79
This topic comprises command sections for Command Line Options and Processing. These sections will be conducted in the following manner: Instructions: Explain the command with demonstration. Ask participants to execute the same. Discuss the related slide.
Note: The commands would be used by the faculty and participants simultaneously.
73
73 Usage of Shift (1 of 4) For instance: If we have a shell script which takes arguments, e.g., script test which takes f1 and f2 as parameters. If we execute this script: test f1 f2, $1 becomes f1 and $2 becomes f2. What if options are involved e.g., test -a f1
Helps to get a way around above problem shift will make (f1 as $1).
Provides a work-around in case of more than 9 positional parameters to a script
74
74 Usage of Shift (2 of 4) Causes the positional parameters to be moved to the left
Uses default move one
Syntax $shift n
Where n is always a positive number.
75
75 Usage of Shift (3 of 4)
Result
76
76 Module 6 Agenda Topic Name Duration Basic Shell Programming 140 min Flow Control 150 min Command Line Options and Processing 45 min Debugging 50 min
77 Demonstration Instructions For slides 83-85
This topic comprises command sections for Debugging. These sections will be conducted in the following manner: Instructions: Explain the command with demonstration. Ask participants to execute the same. Discuss the related slide.
Note: The commands would be used by the faculty and participants simultaneously.
78
78 Usage of Set (1 of 4) Useful for large scripts Various available options: Option Description -v Shows every statement. Echoes the statements to the screen. Substitutes the values of variables. -x Indicates whether the script has executed the statement Puts a plus sign -n Causes the shell to parse the syntax structures without execution
79
79
Usage of Set (2 of 4) -v Option
Result
80
80
Usage of Set (3 of 4) -x Option
Result
81
81
Usage of Set (4 of 4) -n Option
Result
82
82 Activity 7: Debugging Shell I Activity time: 15 minutes The purpose of this activity is to use and understand debugging options x and v with various looping constructs.
Instructions: Write a shell script which would print n numbers supplied from command line and debug it with -x and -v option.
83
83 Activity 8: Debugging Shell II Activity time: 15 minutes The purpose of this activity is to use and understand debugging concept of Shell with loop and conditional constructs
Instructions: Write a shell script which would confirm whether 11 is a prime number or not. Also debug the script.
84
84 Module Summary Upon completing this module, you should now be able to: List different types of shells Compare the advantages and disadvantages of different shells Describe Shell Script Explain the use of Shell Script Describe Interpreter Role Describe how to execute the Basic Shell Scripting Technique Describe how to execute flow control techniques in Shell Script Describe command line handling in Shell Scripts Explain the Command line processing process Describe how to execute basic Shell Scripting debugging techniques