Shell Script Programming
2 Using UNIX Shell Scripts Unlike high-level language programs, shell scripts do not have to be converted into machine language by a compiler The UNIX shell acts as an interpreter when reading script files Interpreters read statements in script files and immediately translate them into executable instructions and cause them to run
3 Using UNIX Shell Scripts After creating shell script, the OS is instructed that the file is an executable shell script via the chmod command When the file is designated as executable, you may run it in one of many ways: –Type the script name at the command prompt after updating the path variable –If the script is in the current directory, proceed its name at the prompt with a dot slash (./) –If not in the current directory, specify the absolute path at the command prompt
4 Ensuring the Correct Shell Runs the Script In Unix there is more than one shell ! –examples: bash, tcsh, ksh need to ensure that correct shell runs the script different shells use different programming constructs Convention: first line of a script states which executable should run script Example: #! /bin/sh
5 Variables Variables are symbolic names that represent values stored in memory Three types of variables are: –Configuration variables store information about the setup of the OS –Environment variables hold information about your login session –Shell variables are created at the command prompt or in shell scripts and are used to temporarily store information
6 Variables To set: example=one To see: echo $example To make part of the environment: export example To remove: unsetenv example
7 Variables Use the printenv command to see a list of environment variables
8 Some Variables HOME home directory USER user name PATH list of command directories PWD current directory
9 Shell Operators Bash shell operators are in three groups: –Defining and Evaluating operators are used to set a variable to a value and to check variable values The equal sign (=) is an example –Arithmetic operators are used to perform mathematical equations The plus sign (+) is an example –Redirecting and piping operators are used to specify input and output data specifications The greater than sign (>) is an example
10 Shell Operators
11 Wildcard Characters Shell scripts often use wildcard characters Wildcard characters are intended to match filenames and words –Question mark (?) matches exactly one character –Asterisk (*) matches zero or more characters –[chars] defines a class of characters, the glob pattern matches any singles character in the class
12 Shell Logic Structures Four basic logic structures needed for program development are: –Sequential logic –User input –Decision logic –Looping logic –Case logic
13 Sequential Logic commands are executed in the order in which they appear in the script break in sequence occurs when a branch instruction changes the flow of execution by redirecting to another location in the script
14 User input Script can read user data Command: read variable reads user input and assigns text to variable
15 User input Command: read var1 var2 var3 reads 3 words and assigns 3 variables Last variable contains rest of input line
16 User input Command: read –p “enter name: “ name Prompts user, then reads input and assigns to variable
17 User input example
18 Decision Logic Enables your script to execute statement(s) only if a certain condition is true Condition: –result of a command –Comparison of variables or values if statement
19 If statement Syntax: if [ condition ] thenstatementselsestatementsfi
20 Decision Logic example
21 Nested Decision Logic
22 Looping Logic A control structure repeats until some condition exists or some action occurs Two common looping mechanisms: –For loops cycle through a range of values until the last in a set of values is reached –The while loop cycles as long as a particular condition exists
23 For Loop Syntax for var in list dostatementsdone
24 For Loop example Program control structures can be entered from the command line
25 For loop in script
26 Loop with wildcard
27 While Loop Syntax while [ condition ] dostatementsdone
28 Looping Logic The while loop tests repeatedly for a matching condition
29 Looping Logic While loops can serve as data-entry forms
30 While loop to enter data
31 Case Logic The case logic structure simplifies the selection from a list of choices It allows the script to perform one of many actions, depending on the value of a variable Two semicolons (;;) terminate the actions taken after the case matches what is being tested
32 Case statement Syntax: case $variable in “pattern1”)statements;;“pattern2”)statements;;esac
33 Case example
34 Case Logic
35 Debugging a Shell Script Shell script will not execute if there is an error in one or more commands sh has options for debugging –sh -v displays lines of script as they are read by the interpreter –sh -x displays the command and its arguments line by line as they are run
36 Debugging a Shell Script View the script line by line as it is running to help locate errors
37 Using Shell Scripting to Create a Menu A menu is a good example of a shell script that employs the four basic logic structures A significant feature of the menu script is the screen presentation which should be as appealing and user-friendly as possible
38 tput command tput clear –clear the screen tput cup r c –position cursor to row and column –ex: tput cup 0 0 tput cup tput cup bold=`tput smso` offbold=`tput rmso`
39 Example tput clear; tput cup 10 15; echo “Hello”; tput cup 20 0
40 Creating a Menu tput can be used to help create data entry screens
41 Creating a Menu
42 Creating a Menu tput can be used to help create user menus
43 Creating a Menu
44 The trap Command used to guard against abnormal termination of script –user ^C –OS intervention normal: remove temporary file example: trap ’rm ~/tmp/*’ 2 15
45 The awk Command Allows simple formatting of output –Reads input line by line –Line contains fields (need field separator) –Use C printf command to format output
46 Example: corp_phones awk -F ':' ‘{printf("%-12s %-10s %10s\n",$2,$3,$1)}’ corp_phones
47 Shell script: phoneadd The phoneadd script allows to add new records to the corp_phones file
48 Shell script: phoneadd
49 Complete script: phmenu
50 Script parameters Command line invocation may list parameters Example: myscript one two three Available inside scripts as $1, $2, $3
51 Parameter example
52 Script Parameters
53 More Script Parameters
54 Numeric variables Let command defines integer variables with numeric values Example: let i=1 let i=5*i-2 Let command allows simple numeric calculations
55 Using the test Command Bash shell uses test command to: –perform relational tests with integers –test and compare strings –check if a file exists and what type of file it is –perform Boolean tests Test command is standard Unix command Is used in bash for if and while statements
56 Using the test command Syntax: test some-expression [ some-expression ] Indicates result via exit status –0 is true, 1 is false To get exit status: echo $?
57 Relational Integer Tests
58 String Tests
59 Testing Files
60 Performing Boolean Tests
61 Using the test Command
62 Quoting Double quotes example: text=“hello world” echo “here it is: $text” echo “here it is: $text” Single quotes example: text=‘one two three’ echo “here it is: $text” echo “here it is: $text” Execution quote example: text=`date` echo “here it is: $text” echo “here it is: $text”
63 Review: sed Can be used to remove lines from a file Syntax: sed ‘/pattern/d’ file1 > file2 Removes all lines which match the pattern from file1
64 Deleting Phone Records The menu has been updated to allow for deleting a phone record
65 Deleting Phone Records Examine the corp_phones file before deleting a record
66 Deleting Phone Records The sed command is behind the delete option
67 Deleting Phone Records The record is no longer in the file
68 Shell functions Used to group recurring code Syntax: functionname() { commands}
69 Shell function example datenow() { date}it=`datenow` echo $it
70 Shell function parameters checkfile() { echo “Checking: $1” if [ -f “$1” ] then echo “$1 is a file” else if [ -d “$1” ] then echo “$1 is a directory” fifi} checkfile phmenu