Shell Script Programming. 2 Using UNIX Shell Scripts Unlike high-level language programs, shell scripts do not have to be converted into machine language.

Slides:



Advertisements
Similar presentations
CIS 240 Introduction to UNIX Instructor: Sue Sampson.
Advertisements

Introduction to Unix – CS 21 Lecture 11. Lecture Overview Shell Programming Variable Discussion Command line parameters Arithmetic Discussion Control.
A Guide to Unix Using Linux Fourth Edition
A Guide to Unix Using Linux Fourth Edition
CS Lecture 03 Outline Sed and awk from previous lecture Writing simple bash script Assignment 1 discussion 1CS 311 Operating SystemsLecture 03.
Linux+ Guide to Linux Certification, Second Edition
More Shell Basics CS465 - Unix. Unix shells User’s default shell - specified in /etc/passwd file To show which shell you are currently using: $ echo $SHELL.
Guide To UNIX Using Linux Third Edition
Guide To UNIX Using Linux Third Edition
Introduction to Unix (CA263) Introduction to Shell Script Programming By Tariq Ibn Aziz.
Bash Shell Scripting 10 Second Guide Common environment variables PATH - Sets the search path for any executable command. Similar to the PATH variable.
Shell Programming. Shell Scripts (1) u Basically, a shell script is a text file with Unix commands in it. u Shell scripts usually begin with a #! and.
Shell Script Examples.
Fundamentals of Python: From First Programs Through Data Structures
CTEC 1863 – Operating Systems Shell Scripting. CTEC F2 Overview How shell works Command line parameters –Shift command Variables –Including.
Shell Programming, or Scripting Shirley Moore CPS 5401 Fall August 29,
Ch 111 Chapter 11 Advanced Batch Files. Ch 112 Overview This chapter focuses on batch file commands that allow you to:  write sophisticated batch files.
Shell Scripting Awk (part1) Awk Programming Language standard unix language that is geared for text processing and creating formatted reports but it.
Chapter Seven Advanced Shell Programming. 2 Lesson A Developing a Fully Featured Program.
Advanced Shell Programming. 2 Objectives Use techniques to ensure a script is employing the correct shell Set the default shell Configure Bash login and.
Fundamentals of Python: First Programs
Agenda Control Flow Statements Purpose test statement if / elif / else Statements for loops while vs. until statements case statement break vs. continue.
Introduction to Shell Script Programming
1 Operating Systems Lecture 3 Shell Scripts. 2 Shell Programming 1.Shell scripts must be marked as executable: chmod a+x myScript 2. Use # to start a.
1 Operating Systems Lecture 3 Shell Scripts. 2 Brief review of unix1.txt n Glob Construct (metacharacters) and other special characters F ?, *, [] F Ex.
8 Shell Programming Mauro Jaskelioff. Introduction Environment variables –How to use and assign them –Your PATH variable Introduction to shell programming.
Week 7 Working with the BASH Shell. Objectives  Redirect the input and output of a command  Identify and manipulate common shell environment variables.
Chapter 6: Shell Programming
An Introduction to Unix Shell Scripting
Input, Output, and Processing
Linux+ Guide to Linux Certification, Third Edition
Writing Shell Scripts ─ part 3 CSE 2031 Fall October 2015.
Linux Operations and Administration
UNIX Shell Script (1) Dr. Tran, Van Hoai Faculty of Computer Science and Engineering HCMC Uni. of Technology
Course materials may not be reproduced in whole or in part without the prior written permission of IBM. 5.1 © Copyright IBM Corporation 2008 Unit 11: Shell.
CS465 - UNIX The Bourne Shell.
Shell Programming. Introducing UNIX Shells  Shell is also a programming language and provides various features like variables, branching, looping and.
Linux+ Guide to Linux Certification Chapter Eight Working with the BASH Shell.
Shell Programming. Creating Shell Scripts: Some Basic Principles A script name is arbitrary. Choose names that make it easy to quickly identify file function.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
Review Chapters 5 thru 8. 2 Two Groups of Commands Select commands Manipulate and Format commands.
Chapter Three The UNIX Editors.
Writing Scripts Hadi Otrok COEN 346.
LIN Unix Lecture 5 Unix Shell Scripts. LIN Command Coordination ; && || command1 ; command2 Interpretation: Do command 1. Then do command.
©Colin Jamison 2004 Shell scripting in Linux Colin Jamison.
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
Shell Scripting – Putting it All Together. Agenda Escaping Characters Wildcards Redirecting Output Chaining and Conditional Chaining Unnamed and Named.
Chapter Six Introduction to Shell Script Programming.
CSCI 330 UNIX and Network Programming Unit IX: Shell Scripts.
Lesson 3-Touring Utilities and System Features. Overview Employing fundamental utilities. Linux terminal sessions. Managing input and output. Using special.
Agenda Positional Parameters / Continued... Command Substitution Bourne Shell / Bash Shell / Korn Shell Mathematical Expressions Bourne Shell / Bash Shell.
Linux+ Guide to Linux Certification, Second Edition
Assigning Values 1. $ set One Two Three [Enter] $echo $1 $2 $3 [Enter] 2. $set `date` [Enter] $echo $1 $2 $3 [Enter] 3. $echo $1 $2 $3 $4 $5 $6 [Enter]
Lesson 8-Specifying Instructions to the Shell. Overview An overview of shell. Execution of commands in a shell. Shell command-line expansion. Customizing.
1 Lecture 7 Introduction to Shell Scripts COP 3353 Introduction to UNIX.
Linux Administration Working with the BASH Shell.
INTRODUCTION TO SHELL SCRIPTING By Byamukama Frank
COMP075 OS2 Bash Scripting. Scripting? BASH provides access to OS functions, like any OS shell Also like any OS shell, BASH includes the ability to write.
Lecture 7 Introduction to Shell Programming
Lecture 7 Introduction to Shell Scripts COP 3353 Introduction to UNIX.
Shell Features CSCI N321 – System and Network Administration
Agenda Bash Shell Scripting – Part II Logic statements Loop statements
Shell Script Assignment 1.
Writing Shell Scripts ─ part 3
Writing Shell Scripts ─ part 3
Agenda Control Flow Statements Purpose test statement
Pepper (Help from Dr. Robert Siegfried)
Linux Shell Script Programming
Introduction to Bash Programming, part 3
Bash Scripting CS 580U - Fall 2018.
Presentation transcript:

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