Chapter 6: Shell Programming

Slides:



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

A Guide to Unix Using Linux Fourth Edition
CS 497C – Introduction to UNIX Lecture 32: - Shell Programming Chin-Chih Chang
CS 497C – Introduction to UNIX Lecture 22: - The Shell Chin-Chih Chang
CS Lecture 03 Outline Sed and awk from previous lecture Writing simple bash script Assignment 1 discussion 1CS 311 Operating SystemsLecture 03.
Shell Programming Software Tools. Slide 2 Shells l A shell can be used in one of two ways: n A command interpreter, used interactively n A programming.
Linux+ Guide to Linux Certification, Second Edition
Scripting Languages and C-Shell. What is a scripting language ? Script is a sequence of commands written as plain text and run by an interpreter (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.
Shell Scripts 4 A shell usually interprets a single line of input, but we can also create a file containing a number of lines of commands to be interpreted.
Unix Shell Scripts. What are scripts ? Text files in certain format that are run by another program Examples: –Perl –Javascript –Shell scripts (we learn.
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.
Shell Control Structures CSE 2031 Fall August 2015.
Shell Programming, or Scripting Shirley Moore CPS 5401 Fall August 29,
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.
High-Level Programming Languages: C++
Introduction to Shell Script Programming
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.
An Introduction to UNIX System --- Cosc513 Presentation n Instructor: Morteza Anvari n Author: Yonghong Pan n ID#: n Date: Jan.29, 2001.
An Introduction to Unix Shell Scripting
The UNIX Shell. The Shell Program that constantly runs at terminal after a user has logged in. Prompts the user and waits for user input. Interprets command.
Introduction to Unix – CS 21 Lecture 9. Lecture Overview Shell description Shell choices History Aliases Topic review.
Writing C-shell scripts #!/bin/csh # Author: Ken Berman # Date: # Purpose: display command and parameters echo $0 echo $argv[*]
July 17, 2003Serguei A. Mokhov, 1 Shells and Shell Scripts COMP 444/5201 Revision 1.3 January 25, 2005.
Shell Script Programming. 2 Using UNIX Shell Scripts Unlike high-level language programs, shell scripts do not have to be converted into machine language.
1 Shell Scripting (C shell) SungHo Maeung 10/27/2000 Tutorial section Computer Science Lab.
Lecture 4  C Shell Scripts(Chapter 10). Shell script/program  Shell script: a series of shell commands placed in an ASCII text file  Commands include.
LINUX System : Lecture 6 Shell Programming
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
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.
1 System Administration Introduction to Scripting, Perl Session 3 – Sat 10 Nov 2007 References:  chapter 1, The Unix Programming Environment, Kernighan.
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.
LIN Unix Lecture 7 Hana Filip. LIN Text Processing Command Line Utility Programs (cont.) sed LAST WEEK wc sort tr uniq awk TODAY join paste.
Writing Scripts Hadi Otrok COEN 346.
Shell Programming Learning Objectives: 1. To understand the some basic utilities of UNIX File 2. To compare UNIX shell and popular shell 3. To learn the.
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.
UNIX shell environments CS 2204 Class meeting 4 Created by Doug Bowman, 2001 Modified by Mir Farooq Ali, 2002.
1 Lecture 9 Shell Programming – Command substitution Regular expressions and grep Use of exit, for loop and expr commands COP 3353 Introduction to UNIX.
1 © 2000 John Urrutia. All rights reserved. Session 5 The Bourne Shell.
Chapter Six Introduction to Shell Script Programming.
Agenda Positional Parameters / Continued... Command Substitution Bourne Shell / Bash Shell / Korn Shell Mathematical Expressions Bourne Shell / Bash Shell.
1 Unix/Linux commands and shell programming-Part 2 (Dr. Mohamed El Bachir Menai)
Linux+ Guide to Linux Certification, Second Edition
Introduction to Bash Shell. What is Shell? The shell is a command interpreter. It is the layer between the operating system kernel and the user.
1 Lecture 7 Introduction to Shell Scripts COP 3353 Introduction to UNIX.
Chapter 16 Advanced Bourne Shell Programming. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Objectives To discuss numeric data processing.
Linux Administration Working with the BASH Shell.
INTRODUCTION TO SHELL SCRIPTING By Byamukama Frank
CS 350 Lecture 3 UNIX/Linux Shells by İlker Korkmaz and Kaya Oğuz.
Lecture 7 Introduction to Shell Programming
SUSE Linux Enterprise Desktop Administration
Lecture 7 Introduction to Shell Scripts COP 3353 Introduction to UNIX.
Agenda Korn Shell Functions Korn Shell Variables
Bash Introduction (adapted from chapters 1 and 2 of bash Cookbook by Albing, Vossing, & Newham) CPTE 440 John Beckett.
LINUX System : Lecture 5 (English-Only Lecture)
Shell Programming.
Linux Shell Script Programming
Review The Unix Shells Graham Glass and King Ables,
Presentation transcript:

Chapter 6: Shell Programming Shell Scripts

Using the UNIX Shell as a Programming Objectives: After studying this lesson, you should be able to: Learn about shell variables, operators Write simple shell scripts to illustrate programming logic

My first Shell Script vi myfirstscript.sh #! /bin/csh set directory=`pwd` echo The date today is `date` echo The current directory is $directory chmod u+x myfirstscript.sh myfirstscript.sh

Using UNIX Shell Scripts UNIX shell scripts are text files that contain sequences of UNIX commands Like high-level source files, a programmer creates shell scripts with a text editor Shell scripts do not have to be converted into machine language by a compiler This is because the UNIX shell acts as an interpreter when reading script files

Using UNIX Shell Scripts Continued As an interpreter reads the statements in a program file, it immediately translates them into executable instructions, and causes them to run After you create a shell script, you simply tell the operating system that the file is a program that can be executed This is accomplished by using the chmod command to change the files’ mode

Using UNIX Shell Scripts Continued Further, the chmod command tells the computer who is allowed to use the file: the owner (u), the group (g), or all other users (o) Shell programs run less quickly than do compiled programs, because the shell must interpret each UNIX command inside the executable script file before it is executed

The Programming Shell Commonly used shell in most variant of UNIX are: Bourne Shell (sh), first shell developed for UNIX Bourne Again Shell (bash), written by programmers of Free Software Foundation, open source shell from GNU Korn Shell (ksh), written by David Korn, superset of Bourne shell, not widely distributed. C Shell (csh), written by Bill Joy, the author of vi, shared much of the C language structure. Terminal Based C Shell (tcsh), enhanced version of the Berkeley UNIX C shell csh

The Programming Shell All Linux versions use the Bash shell (Bourne Again Shell) as the default shell All UNIX system include C shell and its predecessor Bourne shell.

Shell Programming Shell variables Operators Logic structures programming features of the UNIX shell: Shell variables Operators Logic structures

Shell Programming programming features of the UNIX shell: Shell variables: Your scripts often need to keep values in memory for later use. Shell variables are symbolic names that can access values stored in memory Operators: Shell scripts support many operators, including those for performing mathematical operations Logic structures: Shell scripts support sequential logic (for performing a series of commands), decision logic (for branching from one point in a script to another), looping logic (for repeating a command several times), and case logic (for choosing an action from several possible alternatives)

Shell Programming Shell variables Operators Logic structures programming features of the UNIX shell: Shell variables Operators Logic structures

Variables Variables are symbolic names that represent values stored in memory The three types of variables discussed in this section are configuration variables, environment variables, and shell variables Use configuration variables to store information about the setup of the operating system, and do not change them You can set up environment variables with initial values that you can change as needed

Variables Continued These variables, which UNIX reads when you log in, determine many characteristics of your session Shell variables are those you create at the command line or in a shell script Environment and configuration variables bear standard names, such as HOME, PATH, SHELL, USERNAME, and PWD (Configuration and environment variables are capitalized to distinguish them from user variables)

To see a list of your environment variables: $ printenv or: Variables Continued To see a list of your environment variables: $ printenv or: $ printenv | more

Variables Continued 1. Typical Environment Variables HOME: pathname of your home directory PATH: directories where shell is to look for commands USER: your user name PWD: your current working directory MAIL: pathname of your system mailbox SHELL: pathname of your shell 2. Variable contents are accessed using ‘$’: e.g. $ echo $HOME

Variables Continued A shell variable take on the generalized form variable=value (except in the C shell). $ x=37; echo $x $ 37 $ unset x; echo $x The C shell uses the set statement set variables. $ set x = 37 You can set a pathname or a command to a variable or substitute to set the variable. $ set mydir=`pwd`; echo $mydir

To create lists: $ set Y = (UNL 123 CS251) To set a list element: Variables Continued To create lists: $ set Y = (UNL 123 CS251) To set a list element: $ set Y[2] = HUSKER To view a list element: $ echo $Y[2]

myinputs.sh HUSKER UNL CSE Variables Continued vi myinputs.sh #! /bin/csh echo Total number of inputs: $#argv echo First input: $argv[1] echo Second input: $argv[2] chmod u+x myinputs.sh myinputs.sh HUSKER UNL CSE

Shell Programming Shell variables Operators Logic structures programming features of the UNIX shell: Shell variables Operators Logic structures

Shell Operators The Bash shell operators are divided into three groups: defining and evaluating operators, arithmetic operators, and redirecting and piping operators

expr supports the following operators: Arithmetic Operators expr supports the following operators: arithmetic operators: +,-,*,/,% comparison operators: <, <=, ==, !=, >=, > boolean/logical operators: &, | parentheses: (, ) precedence is the same as C, Java

Arithmetic Operators (example) vi math.sh #!/bin/csh set count=5 set count=`expr $count + 1` echo $count chmod u+x math.sh math.sh

Shell Programming Shell variables Operators Logic structures programming features of the UNIX shell: Shell variables Operators Logic structures

Shell Logic Structures The four basic logic structures needed for program development are: Sequential logic Decision logic Looping logic Case logic

Sequential Logic Sequential logic states that commands will be executed in the order in which they appear in the program The only break in this sequence comes when a branch instruction changes the flow of execution

Decision Logic Decision logic enables your program to execute a statement or series of statements only if a certain condition exists The if statement is the primary decision-making control structure in this type of logic

Decision Logic (continued) if-then if ( expr ) simple-command if-then-else if ( expr ) then command-set-1 [else command-set-2] endif

Decision Logic (continued) A simple example #!/bin/csh if ($#argv != 2) then echo $0 needs two parameters! echo You are inputting $#argv parameters. else set par1 = $argv[1] set par2 = $argv[2] endif

Decision Logic (continued) Another example: #! /bin/csh # number is positive, zero or negative echo "enter a number:" set number = $< if ( $number < 0 ) then echo "negative" else if ( $number == 0 ) then echo zero else echo positive endif

Decision Logic (continued) Another example: #!/bin/csh if {( grep UNIX $argv[1] > /dev/null )} then echo UNIX occurs in $argv[1] else echo No! echo UNIX does not occur in $argv[1] endif Redirect intermediate results into >/dev/null, instead of showing on the screen.

Looping Logic In looping logic, a control structure (or loop) repeats until some condition exists or some action occurs You will learn two looping mechanisms in this section: the for loop and the while loop You use the for command for looping through a range of values. It causes a variable to take on each value in a specified set, one at a time, and perform some action while the variable contains each individual value

The while Loop A different pattern for looping is created using the while statement The while statement best illustrates how to set up a loop to test repeatedly for a matching condition The while loop tests an expression in a manner similar to the if statement As long as the statement inside the brackets is true, the statements inside the do and done statements repeat

Looping Logic while ( expr ) command_set end foreach var ( worddlist )

Looping Logic Program: #!/bin/csh foreach person (Bob Susan Joe Gerry) echo Hello $person end Output: Hello Bob Hello Susan Hello Joe Hello Gerry

Adding integers from 1 to 10 Looping Logic Adding integers from 1 to 10 #!/bin/csh set i=1 set sum=0 while ($i <= 10) echo Adding $i into the sum. set sum=`expr $sum + $i` set i=`expr $i + 1` end echo The sum is $sum.

Switch Logic The switch logic structure simplifies the selection of a match when you have a list of choices It allows your program to perform one of many actions, depending upon the value of a variable

Switch Logic switch ( var ) case string1: command_set_1 breaksw default command_set_3 endsw

Switch Logic #!/bin/csh if ($#argv == 0 ) then echo "No arguments supplied...exiting" else switch ($argv[1]) case [yY]: echo Argument one is yes. breaksw case [nN]: echo Argument one is no. default: echo Argument one is neither yes nor no. endsw endif

Chapter Summary A high-level language must be converted into a low-level (machine) language before the computer can execute it The shell interprets UNIX shell scripts UNIX shell scripts, created with the vi or other editor, contain instructions that do not need to be written from scratch, but rather can be selectively chosen from the operating system’s inventory of executable commands

Chapter Summary Section A Continued Linux shells are derived from the UNIX Bourne, Korn, and C shells UNIX keeps three types of variables: Configuration Environment Shell The shell supports numerous operators, including many for performing arithmetic operations The logic structures supported by the shell are sequential, decision, looping, and case

Please refer to handout. Homework 1 Please refer to handout.