CST8177 bash Scripting Chapters 13 and 14 in Quigley's "UNIX Shells by Example"

Slides:



Advertisements
Similar presentations
CST8177 bash Scripting Chapters 13 and 14 in Quigley's "UNIX Shells by Example"
Advertisements

Introduction to Unix – CS 21 Lecture 11. Lecture Overview Shell Programming Variable Discussion Command line parameters Arithmetic Discussion Control.
More about Shells1-1 More about Shell  Shells (sh, csh, ksh) are m Command interpreters Process the commands you enter m High-level programming languages.
CS Lecture 03 Outline Sed and awk from previous lecture Writing simple bash script Assignment 1 discussion 1CS 311 Operating SystemsLecture 03.
Chapter 5: Loops and Files.
CS 497C – Introduction to UNIX Lecture 34: - Shell Programming Chin-Chih Chang
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 Script Examples.
Shell Programming, or Scripting Shirley Moore CPS 5401 Fall August 29,
Chapter 15 Introductory Bash Programming
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.
Introduction to UNIX / Linux - 11
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.
Shell Scripting Todd Kelley CST8207 – Todd Kelley1.
CST8177 bash Scripting Chapters 13 and 14 in Quigley's "UNIX Shells by Example"
More Scripting Todd Kelley CST8207 – Todd Kelley1.
Introduction to Linux OS (IV) AUBG ICoSCIS Team Prof. Volin Karagiozov March, 09 – 10, 2013 SWU, Blagoevgrad.
Linux+ Guide to Linux Certification, Third Edition
Writing Shell Scripts ─ part 3 CSE 2031 Fall October 2015.
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.
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.
CSC 352– Unix Programming, Spring 2015 March 2015 Shell Programming (Highlights only)
Meet Perl, Part 2 Flow of Control and I/O. Perl Statements Lots of different ways to write similar statements –Can make your code look more like natural.
1 © 2001 John Urrutia. All rights reserved. Chapter 10 using the Bourne Again Shell.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
CPS120: Introduction to Computer Science Decision Making in Programs.
Chapter 10: BASH Shell Scripting Fun with fi. In this chapter … Control structures File descriptors Variables.
1 CS161 Introduction to Computer Science Topic #9.
JavaScript, Fourth Edition
©Colin Jamison 2004 Shell scripting in Linux Colin Jamison.
Perl Tutorial. Why PERL ??? Practical extraction and report language Similar to shell script but lot easier and more powerful Easy availablity All details.
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
1 Lecture 9 Shell Programming – Command substitution Regular expressions and grep Use of exit, for loop and expr commands COP 3353 Introduction to UNIX.
UNIX Command RTFM: trap(1p) Gilbert Detillieux October 8, 2013 MUUG Meeting.
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.
Loops and Files. 5.1 The Increment and Decrement Operators.
Sed. Class Issues vSphere Issues – root only until lab 3.
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.
CSCI 330 UNIX and Network Programming Unit X: Shell Scripts II.
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]
S -1 Processes. S -2 wait and waitpid (11.2) Recall from a previous slide: pid_t wait( int *status ) wait() can: (a) block; (b) return with status; (c)
Various 2. readonly readonly x=4 x=44 #this will give an error (like what in java?)
1 UNIX Operating Systems II Part 2: Shell Scripting Instructor: Stan Isaacs.
Shell Scripting September 27, 2004 Class Meeting 6, Part II * Notes adapted by Lenwood Heath from previous work by other members of the CS faculty at Virginia.
Linux Administration Working with the BASH Shell.
1 Lecture 8 Shell Programming – Control Constructs COP 3353 Introduction to UNIX.
Introduction to the bash Shell (Bourne-Again SHell)
Chapters 13 and 14 in Quigley's "UNIX Shells by Example"
CSC 352– Unix Programming, Fall 2012
Shell Scripting March 1st, 2004 Class Meeting 7.
Shell Programming (ch 10)
CSE 303 Concepts and Tools for Software Development
Writing Shell Scripts ─ part 3
Programmazione I a.a. 2017/2018.
Agenda Control Flow Statements Purpose test statement
What is Bash Shell Scripting?
Pepper (Help from Dr. Robert Siegfried)
CHAPTER 8 (skip , ) CHAPTER 10
Linux Shell Script Programming
CSC 352– Unix Programming, Fall, 2011
CST8177 Scripting 2: What?.
Introduction to Bash Programming, part 3
Presentation transcript:

CST8177 bash Scripting Chapters 13 and 14 in Quigley's "UNIX Shells by Example"

Signals and the TRAP statement Page in Quigley. Various signals can be trapped and your own script code executed instead of the system's normal code. Although there are up to 64 signals available, we will consider only a few of them: SIGHUP (signal 1 or HUP: hang up) is issued for a remote connection when the connection is lost or terminated; it's also used to tap a daemon on the shoulder, to re-read its config files. SIGINT (signal 2 or INT) is the keyboard interrupt signal given by Control-C. SIGKILL (signal 9 or KILL) cannot be ignored or trapped. SIGTERM (signal 15 or TERM) is the default signal used by kill(1) and killall(1).

Signal-like events and TRAP The EXIT event (also "signal" 0) occurs upon exit from the current shell. The DEBUG event takes place before every simple command, for command, case command, select command, and before the first command in a function. See also the description of extdebug for the shopt built-in for details of its effect. The ERR event takes place for each simple command with a non-zero exit status, subject to these conditions: it is not executed if the failed command is part of a while, until, or if condition expression, or in a && or || list, or if the command’s return value is being inverted via !. See also errexit for details. The RETURN event occurs each time a shell function or a script executed with the. (that's a dot) or source built-in returns to its caller.

Signals and the TRAP statement You can set a trap: trap 'statement; statement; …' event-list The trap statement list is read by the shell twice, first when it's set (it's set once only, before it is to be used, and stays active until you clear it). It's read a second time when it's executed. If you enclose the statement in single quotes, substitutions only take place at execution time. If you use double quotes, substitutions will take place upon both readings. If statement is omitted, the signals (use - (dash)) for all) are reset to the default. If statement is a null (empty) string, the signals specified will be ignored.

Signals and the TRAP statement To set a trap for SIGINT: trap 'statement; statement; …' INT To turn it off again: trap INT To prevent any SIGINT handling (ignore signals): trap " " INT Be cautious in trapping SIGINT: how will you stop a run-away script? To see what traps are set (you can see traps for specific events by listing the names or numbers): trap -p To list the names for signals 1 to SIGRTMAX: trap -l# that's an ell, not a one

Trap Sample Script #! /bin/bash declare -i count=0 # set trap to echo, then turn itself off trap 'echo -e \\nSIGINT ignored in $count; \ trap sigint;' sigint # loop forever while (( 1 == 1 )); do let count++ read -p "$count loop again? " done # if loop ends, display count echo loop count $count exit 0

System Prompt$./my-trap 1 loop again? 2 loop again? 3 loop again? 4 loop again? y 5 loop again? n 6 loop again? 7 loop again? q 8 loop again? help 9 loop again? ^C SIGINT ignored in 9 10 loop again? q 11 loop again? y 12 loop again? n 13 loop again? ^C System Prompt$

Functions in bash You will learn that functions are exceptionally useful, and it's good to see them in bash. Pages in Quigley A function is a group of regular shell-script statements is a self-contained package. You define a function as: function somename () { statement … } And you call it by using the name as if it were a normal command.

bash Functions A function does not need to return a result, but it may do so in 3 ways (perhaps all in the same function): 1. set a new value into a variable previously defined outside the function; 2. Use a return statement to set the value of $?; it can also use an exit to set $?, but that will also exit from the calling script which may not be what you want. 3. write the results to stdout.

Functions Function scope is from the point the function is defined to the end of the file (that is, it must be defined before you can use it). Generally, that means that all functions precede the main body of the script. As a result, previously-written functions are often included in a script using the source (also. (dot)) statement near the top of a script. You can define local variables to be used only inside the function, while your normal variables from outside the function can always be used. If you wish, you can pass arguments into a function as positional parameters ($1 and so on; this is by far the recommended approach).

Functions You may have noticed that traps behave like a special form of function. They are called (or invoked) by an event and consist of a collection of command statements. This is not an accident. To unset (delete or remove) a function: unset -f functionname To list defined function names (note: my system seems to have over 400 functions, of which I have only defined 4 of my own): declare -F | less To list functions and definitions: declare -f [functionname]

A Simple Sample The rot13 script is an implementation of the Caesar code message encryption. It simply rotates the message 13 characters through the alphabet, retaining case. No numbers or punctuation characters are affected. rot13 () { echo "$*" | \ tr '[a-mA-Mn-zN-Z]' '[n-zN-Za-mA-M]' return 0 } As you can see, rot13 accepts command-line arguments which it passes via echo through a translate (tr) command that will print the result on stdout. Entering rot13 sheesh produces furrfu on stdout, while the reversed rot13 fuurfu displays sheesh.

When to write a function There are a lot of scripting situations where writing a short function of your own is a good idea. Some of these include: Some common activity that will be used frequently Part of a larger script that will be repeated at least 2 or 3 times, perhaps slightly differently each time An uncommon activity used only once in a while, but you don't want to have to remember the details A tricky bit of logic – write once, use over and over, even if its not often A part of a large script that will only be used once The "Lego block" approach to scripting – develop functions that can be "plugged together" to form a complete script with a little "glue"

Sample function START perms SOURCE file of functions SOURCE file of configuration info SET dir to arg 1 if present SET dir to. if no dir PUT config file values FOR each file in the directory CALL my-format with the current file name END FOR EXIT 0 END perms

Sample function START my-format USING $1 COMMAND for directory/file EXTRACT permissions PUT directory/file and permissions RETURN 0 END my-format Data Dictionary (Global) NameTypeValuePurpose CMDstringls -ldCommand to execute DELIMstring" Delimiter for cut DIRstringundefinedDirectory to use FIELDinteger1Field number for cut

Sample function In file./config: CMD='ls -ld' FIELD=1 DELIM=' ' In file./include: function my-format () { echo file \"$DIR/$1\" permissions \ $($CMD $DIR/$1 \ | cut -f $FIELD -d "$DELIM") return 0 } Note file permissions: -rw-rw-r--. 1 allisor allisor 31 date config -rw-rw-r--. 1 allisor allisor 121 date include

#! /bin/bash # source my files source./include # function here source./config # variables here # set default directory to $1 or. DIR=${1:-$DIR} DIR=${DIR:-.} # show config values echo Config: CMD = \"$CMD\"\; \ FIELD = \"$FIELD\"\; DELIM = \"$DELIM\" # do some stuff with the function for x in $(ls $DIR); do my-format $x done exit 0

Execution of the script System Prompt$./perms Config: CMD = "ls -l"; FIELD = "1"; DELIM = " " file "./config" permissions -rw-rw-r--. file "./include" permissions -rw-rw-r--. file "./perms" permissions -rwxrwxr-x. System Prompt$ What's happening? Both./include and./config are brought into the perms script as though they had been written there. Then each time through the for loop, the next filename is passed to the function my-format. Once it has done its work, control returns to the calling script, perms, where it goes through the loop again until the list is exhausted.

The getops Function Many scripts depend heavily upon command line arguments, or positional parameters, so writers frequently use the getopts function to make processing them easier. It's often used for the -x form (the "dash" form) of options because of all the many combinations. For example, consider a command which can have options -x, -y, and -z in any order and any combination (like -xz and -zx), giving at least 29 (I counted) valid combinations. You don't want to write script code for each possibility!

getops getopts optionstring variable [argumentlist] It will use the positional parameters unless the optional argumentlist is supplied. getopts puts the matching option character into your variable and puts the number of the next char into OPTIND. If the option is not matched, variable is set to "?" and an error message is written to stderr (unless ":" is the first character of optionstring to suppress that behaviour). Dash arguments that have arguments themselves (like cut -f 5) can be followed by a colon in optionlist, and the next item in the parameter list will be assigned to OPTARG for use in the script. Processing stops when the first non-dash argument is found.

getops Example (./goe) #! /bin/bash declare opt_char while getopts :xy:z opt_char; do

while getopts :xy:z opt_char; do #repeated case $opt_char in x) echo $opt_char found ;; y) echo $opt_char found \ with \"$OPTARG\" ;; z) echo $opt_char found ;; *) echo option error index \ $(( $OPTIND - 1 )) = \"$opt_char\" exit 1 ;; esac done

if (( $OPTIND > $# )); then echo All args have been processed else echo First non-dash arg is \ \$$OPTIND = \"$(eval echo -n \$$OPTIND)\" fi exit 0

System Prompt$./goe All args have been processed System Prompt$./goe x First non-dash arg is $1 = "x" System Prompt$./goe -x x found All args have been processed System Prompt$./goe -x -y some-stuff -z x found y found with "some-stuff" z found All args have been processed System Prompt$./goe -x more-stuff x found First non-dash arg is $2 = "more-stuff"