A Guide to Unix Using Linux Fourth Edition

Slides:



Advertisements
Similar presentations
Shell Script Assignment 1.
Advertisements

A Guide to Unix Using Linux Fourth Edition
A Guide to Unix Using Linux Fourth Edition
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.
Linux+ Guide to Linux Certification, Second Edition
Now, return to the Unix Unix shells: Subshells--- Variable---1. Local 2. Environmental.
Guide To UNIX Using Linux Third Edition
Guide To UNIX Using Linux Third Edition
Guide To UNIX Using Linux Third Edition
Guide to Linux Installation and Administration, 2e1 Chapter 6 Using the Shell and Text Files.
Introduction to Unix (CA263) Introduction to Shell Script Programming By Tariq Ibn Aziz.
Shell Script Examples.
Fundamentals of Python: From First Programs Through Data Structures
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 File Processing
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
Introduction to Shell Script Programming
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.
Agenda User Profile File (.profile) –Keyword Shell Variables Linux (Unix) filters –Purpose –Commands: grep, sort, awk cut, tr, wc, spell.
Chapter Four UNIX File Processing. 2 Lesson A Extracting Information from Files.
Guide To UNIX Using Linux Fourth Edition
Chapter 6: Shell Programming
A Guide to Unix Using Linux Fourth Edition
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.
CIS 218 Advanced UNIX1 CIS 218 – Advanced UNIX (g)awk.
Input, Output, and Processing
Shell Script Programming. 2 Using UNIX Shell Scripts Unlike high-level language programs, shell scripts do not have to be converted into machine language.
Advanced File Processing. 2 Objectives Use the pipe operator to redirect the output of one command to another command Use the grep command to search for.
Linux+ Guide to Linux Certification, Third Edition
Linux Operations and Administration
UNIX Shell Script (1) Dr. Tran, Van Hoai Faculty of Computer Science and Engineering HCMC Uni. of Technology
Chapter Five Advanced File Processing Guide To UNIX Using Linux Fourth Edition Chapter 5 Unix (34 slides)1 CTEC 110.
Chapter Five Advanced File Processing. 2 Objectives Use the pipe operator to redirect the output of one command to another command Use the grep command.
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.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Review Chapters 5 thru 8. 2 Two Groups of Commands Select commands Manipulate and Format commands.
Chapter Five Advanced File Processing. 2 Lesson A Selecting, Manipulating, and Formatting Information.
Writing Scripts Hadi Otrok COEN 346.
Linux+ Guide to Linux Certification, Third Edition
©Colin Jamison 2004 Shell scripting in Linux Colin Jamison.
Chapter Six Introduction to Shell Script Programming.
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
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.
Lesson 6-Using Utilities to Accomplish Complex Tasks.
Lesson 8-Specifying Instructions to the Shell. Overview An overview of shell. Execution of commands in a shell. Shell command-line expansion. Customizing.
Chapter 15 Introductory Bourne Shell Programming.
Linux Administration Working with the BASH Shell.
 Prepared by: Eng. Maryam Adel Abdel-Hady
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Topics Designing a Program Input, Processing, and Output
Department of Computer Engineering
SUSE Linux Enterprise Desktop Administration
The Selection Structure
Shell Script Assignment 1.
Guide To UNIX Using Linux Third Edition
Chapter Four UNIX File Processing.
Shell Programming.
Linux Shell Script Programming
CSE 303 Concepts and Tools for Software Development
Introduction to Bash Programming, part 3
Presentation transcript:

A Guide to Unix Using Linux Fourth Edition Chapter 6 Introduction to Shell Script Programming

Objectives Understand the program development cycle Compare UNIX/Linux shells for creating scripts Use shell variables, operators, and wildcard characters Use shell logic structures Employ shell scripting to create a menu A Guide to Unix Using Linux, Fourth Edition

Objectives (continued) Use commands to help debug shell scripts Explain ways to customize your personal environment Use the trap command Develop a menu-based application A Guide to Unix Using Linux, Fourth Edition

Previewing the Application Shell variables temporarily store values in memory for use by a shell script Symbolic name: consists of letters, numbers, or characters References the contents of a variable Often reflects a variable’s purpose or contents Shell scripts support many shell script operators Shell scripts support logic structures Sequential, decision, looping, and case logic Also called control structures A Guide to Unix Using Linux, Fourth Edition

The Program Development Cycle Program development cycle: process of developing an application Step 1: create program specifications Step 2: begin design process Create file formats, screen layouts, and algorithms Algorithm: sequence of procedures, programming code, or commands that result in a program or that can be used as part of a program Step 3: write the actual code Step 4: test and debug A Guide to Unix Using Linux, Fourth Edition

A Guide to Unix Using Linux, Fourth Edition

Using High-Level Languages High-level language: computer language that uses English-like expressions Examples: ADD 1 TO COUNTER (COBOL) counter = counter + 1; (C++) Statements are stored in a source file Created with an editor such as vi or Emacs Compiler reads source file and converts it to machine-language instructions If source file contains syntax errors, it cannot be converted into an executable file A Guide to Unix Using Linux, Fourth Edition

Using UNIX/Linux Shell Scripts Shell scripts contain sequences of commands Interpreted instead of compiled Interpreted by UNIX/Linux shell If a syntax error is encountered, execution halts Must be identified as an executable file Example: $ chmod ugo+x filename <Enter> Can be run in several ways: Enter name at prompt (PATH must be set) Precede name with ./ Provide an absolute path to file Run less quickly than compiled programs A Guide to Unix Using Linux, Fourth Edition

Prototyping an Application Prototype: running model of your application Allows review of final results before committing to design Shell scripts can be used to create prototypes Quickest and most efficient method After prototype is approved, script can be rewritten to run faster using a compiled language (e.g., C++) If script performs well, no need to convert it to a compiled program A Guide to Unix Using Linux, Fourth Edition

Using Comments Comment lines begin with a pound (#) symbol Example: Hands-On Project 5-16 # ======================================================= # Script Name: pact # By: Your initials # Date: November 2009 # Purpose: Create temporary file, pnum, to hold the # count of the number of projects each # programmer is working on. The pnum file # consists of: # prog_num and count fields cut -d: -f4 project | sort | uniq -c | awk ’{printf "%s: %s\n",$2,$1}’ > pnum # cut prog_num, pipe output to sort to remove duplicates # and get count for prog/projects. # output file with prog_number followed by count A Guide to Unix Using Linux, Fourth Edition

Using Comments (continued) Some examples of what you might comment: Script name, author(s), creation date, and purpose Modification date(s) and purpose of each of them Purpose and types of variables used Files that are accessed, created, or modified How logic structures work Purpose of shell functions How complex lines of code work The reasons for including specific commands A Guide to Unix Using Linux, Fourth Edition

The Programming Shell Three shells that come with most Linux distributions A Guide to Unix Using Linux, Fourth Edition

Variables Configuration variables Environment variables Store information about the setup of OS Not typically modified after they are set up Environment variables Initial values can be changed as needed Shell variables are created at command line or in a shell script Useful for temporarily storing information A Guide to Unix Using Linux, Fourth Edition

Environment and Configuration Variables A Guide to Unix Using Linux, Fourth Edition

Environment and Configuration Variables (continued) Use printenv to view list of your current environment and configuration variables Use set (no arguments) to view current Bash shell environment Including environment variables, shell script variables, and shell functions A Guide to Unix Using Linux, Fourth Edition

A Guide to Unix Using Linux, Fourth Edition

A Guide to Unix Using Linux, Fourth Edition

A Guide to Unix Using Linux, Fourth Edition

Shell Variables Basic guidelines for handling shell variables: Omit spaces when you assign a variable without using single/double quotation marks around value To assign a variable that must contain spaces, enclose value in “” or ‘’ To reference a variable, use a $ in front of it or enclose it in { } Use [ ] to refer to a specific value in an array Export a shell variable to make the variable available to other scripts To make a shell variable read-only: readonly fname A Guide to Unix Using Linux, Fourth Edition

Shell Variables (continued) Sample guidelines for naming shell variables: Avoid using dollar sign in variable names Use descriptive names Use capitalization appropriately and consistently If a variable name is to consist of two or more words, use underscores between the words A Guide to Unix Using Linux, Fourth Edition

Shell Operators Bash shell operators are divided into four groups: Defining operators Evaluating operators Arithmetic and relational operators Redirection operators A Guide to Unix Using Linux, Fourth Edition

Defining Operators Defining operators: assigns a value to a variable Examples: NAME=Becky NAME="Becky J. Zubrow" LIST= `ls` A Guide to Unix Using Linux, Fourth Edition

Evaluating Operators Display contents of a variable via an evaluating operator Examples: echo $NAME echo "$NAME" echo '$NAME' A Guide to Unix Using Linux, Fourth Edition

Arithmetic and Relational Operators The usual mathematical precedence rules apply: Multiplication and division are performed before addition and subtraction A Guide to Unix Using Linux, Fourth Edition

Arithmetic and Relational Operators (continued) A Guide to Unix Using Linux, Fourth Edition

Arithmetic and Relational Operators (continued) Shell variables can be used as operands Assuming X has the value 14, the following command stores 18 in Y: let Y=X+4 let is a built-in command for the Bash shell A Guide to Unix Using Linux, Fourth Edition

Redirection Operators Examples: $ set -o noclobber <Enter> $ cat new_file > old_file <Enter> bash: old_file: cannot overwrite existing file $ cat new_file >| old_file <Enter> A Guide to Unix Using Linux, Fourth Edition

Exporting Shell Variables to the Environment Scripts cannot automatically access variables created/assigned on command line or by other scripts You must use export first A Guide to Unix Using Linux, Fourth Edition

Modifying the PATH Variable The shell looks for programs in the PATH ./filename runs script ./ needed if current directory is not in PATH To see the directories in your path: echo $PATH Sample output: /usr/local/bin:/usr/bin:/bin:/usr/X11R6/bin To add the current working directory to the PATH: PATH=$PATH:. A Guide to Unix Using Linux, Fourth Edition

More About Wildcard Characters Wildcard characters are known as glob characters Shell processes glob characters in unquoted arguments for file name generation Glob characters are part of glob patterns Intended to match file names and words Special constructions that appear in glob patterns: ? * [chars] Example: more chap[1-3] <Enter> A Guide to Unix Using Linux, Fourth Edition

Shell Logic Structures The four basic logic structures needed for program development: Sequential logic Decision logic Looping logic Case logic A Guide to Unix Using Linux, Fourth Edition

Sequential Logic Sequential logic: commands are executed in the order in which they appear in the script or program Only break in sequence logic comes when a branch instruction changes the flow of execution Example: Programming Activity Status Report (shown on next slide) A Guide to Unix Using Linux, Fourth Edition

Sequential Logic (continued) #================================================================ # Script Name: practivity # By: MP # Date: November 2009 # Purpose: Generate Programmer Activity Status Report cut -d: -f4 project | sort | uniq -c | awk ’{printf "%s: %s \n",$2,$1}’ > pnum cut -d: -f1-4 programmer | sort -t: +0 -1 | uniq > pnn join -t: -a1 -j1 1 -j2 1 pnn pnum > pactrep # Print the report awk ’ BEGIN { { FS = ":" } { print "\tProgrammer Activity Status Report\n" } { "date" | getline d } { printf "\t %s\n",d } { print "Prog# \t*--Name--* Projects\n" } { print "==============================================\n"} } { printf "%-s\t%-12.12s %-12.12s %s\t%d\n", $1, $2, $3, $4, $5 } ’ pactrep # remove all the temporary files rm pnum pnn pactrep A Guide to Unix Using Linux, Fourth Edition

Decision Logic Decision logic enables your script to execute a statement (or series of) if a certain condition exists if statement: primary decision-making logic structure Example: echo -n "What is your favorite vegetable? " read veg_name if [ "$veg_name" = "broccoli" ] then echo "Broccoli is a healthy choice." else if [ "$veg_name" = "carrots" ] echo "Carrots are great for you." echo "Don't forget to eat your broccoli also." fi A Guide to Unix Using Linux, Fourth Edition

Looping Logic In looping logic, a control structure repeats until a specific condition exists or some action occurs Examples: for loop while loop A Guide to Unix Using Linux, Fourth Edition

The For Loop Use for to loop through a range of values In the example, the loop repeats six times for USERS in john ellen tom becky eli jill do echo $USERS done A Guide to Unix Using Linux, Fourth Edition

Executing Control Structures at the Command Line A Guide to Unix Using Linux, Fourth Edition

Using Wildcard Characters in a Loop The [ ] wildcard characters can be useful in loops Example: for file in chap[1234]; do more $file done A Guide to Unix Using Linux, Fourth Edition

The While Loop while continues to loop and execute statements as long as condition is true Example: echo -n "Try to guess my favorite color: " read guess while [ "$guess" != "red" ]; do echo "No, not that one. Try again. "; read guess done A Guide to Unix Using Linux, Fourth Edition

Case Logic Case logic structure simplifies selection of a match when you have a list of choices Useful for user menus Example: echo -n "Enter your favorite color: "; read color case "$color" in "blue") echo "As in My Blue Heaven.";; "yellow") echo "As in the Yellow Sunset.";; "red") echo "As in Red Rover, Red Rover.";; "orange") echo "As in Autumn has shades of Orange.";; *) echo "Sorry, I do not know that color.";; esac A Guide to Unix Using Linux, Fourth Edition

Using Shell Scripting to Create a Menu Examples: tput cup 0 0 tput clear tput cols A Guide to Unix Using Linux, Fourth Edition

Debugging a Shell Script sh includes several options for debugging A Guide to Unix Using Linux, Fourth Edition

Customizing Your Personal Environment Login script: runs after you log in to your account .bashrc file can be used to establish customizations that take effect for each login session Alias: name that represents another command alias rm="rm -i" A Guide to Unix Using Linux, Fourth Edition

Customizing Your Personal Environment (continued) Example: # .bashrc # Source global definitions if [ -f /etc/bashrc ]; then . /etc/bashrc # if any global definitions are defined # run them first alias rm=’rm -i’ # make sure user is prompted before # removing files alias mv=’mv -i’ # make sure user is prompted before # overlaying files set -o ignoreeof # Do not allow Ctrl-d to log out set -o noclobber # Force user to enter >| to write # over existing files PS1="\w \$" # Set prompt to show working directory A Guide to Unix Using Linux, Fourth Edition

The trap Command Example: trap "rm ~/tmp/* 2> /dev/null; exit" 0 A Guide to Unix Using Linux, Fourth Edition

Putting it All Together in an Application Create a multifunctional application: Assign and manage variables Use shell operators Employ shell logic structures Use additional wildcard characters Use tput for screen initialization and text placement Use trap to clean up temporary files In Hands-On Projects 6-15 through 6-20, you build a multipurpose application A Guide to Unix Using Linux, Fourth Edition

Summary A shell interprets UNIX/Linux shell scripts Scripts are not interpreted, not compiled Shell scripts can be created with any text editor Linux shells are derived from the UNIX Bourne, Korn, and C shells UNIX/Linux employ three types of variables: Configuration, environment, and shell The shell supports many operators Use wildcard characters in shell scripts A Guide to Unix Using Linux, Fourth Edition

Summary (continued) Logic structures supported by the shell: Sequential, decision, looping, and case Use tput to manage cursor placement Customize your .bashrc file Create aliases to simplify commonly used commands Use trap inside a script file to remove temporary files after the script file has been run (exited) A Guide to Unix Using Linux, Fourth Edition

Command Summary A Guide to Unix Using Linux, Fourth Edition

A Guide to Unix Using Linux, Fourth Edition