Review. Preview. Functions. Functions. Functions with Local Variables. Functions with Local Variables 9/11/2017

Similar documents
Shell programming. Introduction to Operating Systems

EECS2301. Example. Testing 3/22/2017. Linux/Unix Part 3. for SCRIPT in /path/to/scripts/dir/* do if [ -f $SCRIPT -a -x $SCRIPT ] then $SCRIPT fi done

Preview. Review. The test, or [, command. Conditions. The test, or [, command (String Comparison) The test, or [, command (String Comparison) 2/5/2019

Title:[ Variables Comparison Operators If Else Statements ]

Bourne Shell Reference

Lab 4: Shell scripting

example: name1=jan name2=mike export name1 In this example, name1 is an environmental variable while name2 is a local variable.

Computer Systems and Architecture

Shells & Shell Programming (Part B)

1. Hello World Bash Shell Script. Last Updated on Wednesday, 13 April :03

Lexical Considerations

Here redirection. Case statement. Advanced Unix Tools Lecture 6 CS214 Spring 2004 Friday March 5, 2004

Computer Systems and Architecture

Conditional Control Structures. Dr.T.Logeswari

1 Lexical Considerations

Lecture 02 The Shell and Shell Scripting

Control Structures. CIS 118 Intro to LINUX

A shell can be used in one of two ways:

Shell Programming (bash)

Bash scripting Tutorial. Hello World Bash Shell Script. Super User Programming & Scripting 22 March 2013

UNIX shell scripting

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

More Scripting Techniques Scripting Process Example Script

Shells and Shell Programming

Shell Scripting. Todd Kelley CST8207 Todd Kelley 1

Shells and Shell Programming

Command Interpreters. command-line (e.g. Unix shell) On Unix/Linux, bash has become defacto standard shell.

bash Execution Control COMP2101 Winter 2019

COP4020 Programming Assignment 1 - Spring 2011

sottotitolo A.A. 2016/17 Federico Reghenzani, Alessandro Barenghi

You may already be familiar with some redirection, such as. which saves the output of the ls command into a file called lsoutput.txt.

Basic Linux (Bash) Commands

Lexical Considerations

Bash scripting basics

CSCI 211 UNIX Lab. Shell Programming. Dr. Jiang Li. Jiang Li, Ph.D. Department of Computer Science

CSCI 2132: Software Development. Norbert Zeh. Faculty of Computer Science Dalhousie University. Shell Scripting. Winter 2019

Cisco IOS Shell. Finding Feature Information. Prerequisites for Cisco IOS.sh. Last Updated: December 14, 2012

Linux shell scripting Getting started *

Lab 5a Shell Script Lab 4 Using Arithmetic Operators in shell script

Bash shell programming Part II Control statements

Log into Linux Reminders: Homework 1 due today; Homework 2 due on Thursday Questions?

Today. Review. Unix as an OS case study Intro to Shell Scripting. What is an Operating System? What are its goals? How do we evaluate it?

Lecture 4. Log into Linux Reminder: Homework 1 due today, 4:30pm Homework 2 out, due next Tuesday Project 1 out, due next Thursday Questions?

Useful Unix Commands Cheat Sheet

Advanced Unix Programming Module 03 Raju Alluri spurthi.com

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

Програмиранев UNIX среда

X Language Definition

CSC Web Programming. Introduction to JavaScript

Linux Shell Scripting. Linux System Administration COMP2018 Summer 2017

SHELL SCRIPT BASIC. UNIX Programming 2014 Fall by Euiseong Seo

Shell script/program. Basic shell scripting. Script execution. Resources. Simple example script. Quoting

9.2 Linux Essentials Exam Objectives

Week 6 Lesson 1: Control-Flow Statements (Continued)

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

EECS2301. Special variables. $* and 3/14/2017. Linux/Unix part 2

TED Language Reference Manual

Last Time. on the website

Shell Programming. Introduction to Linux. Peter Ruprecht Research CU Boulder

SHELL SCRIPT BASIC. UNIX Programming 2015 Fall by Euiseong Seo

RHCE BOOT CAMP. System Administration

COMP 4/6262: Programming UNIX

Bashed One Too Many Times. Features of the Bash Shell St. Louis Unix Users Group Jeff Muse, Jan 14, 2009

bash Args, Signals, Functions Administrative Shell Scripting COMP2101 Fall 2017

CSC 2500: Unix Lab Fall 2016

Mastering Modern Linux by Paul S. Wang Appendix: Pattern Processing with awk

What is Bash Shell Scripting?

BASH SHELL SCRIPT 1- Introduction to Shell

Unit 7. Functions. Need of User Defined Functions

Shell Start-up and Configuration Files

GAWK Language Reference Manual

More Scripting Todd Kelley CST8207 Todd Kelley 1

Table of Contents. 1. Introduction. 2. Environment. 3. Shell Scripting Shell Scripting Introduction

n Group of statements that are executed repeatedly while some condition remains true

YOLOP Language Reference Manual

Flow Control Continued

COMP 2718: Shell Scripts: Part 1. By: Dr. Andrew Vardy

Contents. Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual

% echo $SHELL /usr/local/bin/bash. % sh $

Shell Control Structures

UNIX Shell Scripts. What Is a Shell? The Bourne Shell. Executable Files. Executable Files: Example. Executable Files (cont.) CSE 2031 Fall 2012

bash Tests and Looping Administrative Shell Scripting COMP2101 Fall 2017

CGS 3066: Spring 2015 JavaScript Reference

Shell scripting and system variables. HORT Lecture 5 Instructor: Kranthi Varala

Linux Systems Administration Shell Scripting Basics. Mike Jager Network Startup Resource Center

Perl. Interview Questions and Answers

Algorithmic "imperative" language

CS 25200: Systems Programming. Lecture 10: Shell Scripting in Bash

CS 6353 Compiler Construction Project Assignments

Introduction to Linux Basics Part II. Georgia Advanced Computing Resource Center University of Georgia Suchitra Pakala

Funk Programming Language Reference Manual

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

Program Representations

INd_rasN SOME SHELL SCRIPTING PROGRAMS. 1. Write a shell script to check whether the name passed as first argument is the name of a file or directory.

Object-Oriented Programming

Unix Scripts and Job Scheduling. Overview. Running a Shell Script

28-Nov CSCI 2132 Software Development Lecture 33: Shell Scripting. 26 Shell Scripting. Faculty of Computer Science, Dalhousie University

Assignment clarifications

Prof. Navrati Saxena TA: R. Sachan Bharat Jyoti Ranjan

Language Reference Manual

Transcription:

Review Preview Conditions The test, or [ Command Control Structures if statement if-else-if statement for loop statement while loop statement until loop statement case statement Functions Function with local variable Function with return value Bash recursive function Other Commands break Command continue Command eval exit export expr printf set shift 1 2 Functions Functions You can dene functions in a shell script. SYNTAX: function_name () statement 1 statement 2 Function prototypes cannot placed for calling a function before function denition. A function must be dened before the function call. When a function is called, the positional parameter the script $*, $@, $#, $0, $1, $2,.. and so on are replaced by the parameters to the function. When the function nishes, the positional parameters are restored to their previous values. 3 4 Functions with Local Variables # function.sh: an example for a function denition function_hello() local yourname -n "What is your name?" read yourname " Hello $yourname " "Parameter variables for the function_hello are $@" Functions with Local Variables We can declare local variables within a function by using local keyword which in only in the function scope. If the local variable has same name as a global variable, it overlays that variable, but only within the function "Parameters variables for this shell script are $@" function_hello you your you yours function_hello I mine me mine "Parameters variables for this shell script are $@" 5 6 1

Functions with Local Variables #local.sh for testing local variable # local variable is in the function scope yourlocation() local mylocation -n "where are you now?" read mylocation "He is now in $mylocation " mylocation = "Salisbury" yourlocation "I am now in $mylocation" #!/bin/bash # GlobalLocal.sh # Global and local variables inside a function. LocalGlobal () local loc_var=23 # Declared as local variable. "\"loc_var\" in function = $loc_var" global_var=999 #global variable "\"global_var\" in function = $global_var" LocalGlobal "\"loc_var\" outside function = $loc_var" "\"global_var\" outside function = $global_var" 7 8 Function with Return Value In bash, we can dene a function with a return value. A function can return 0 (true) or 1(false) as a result. # myname.sh: demonstrate a function with return value yes_or_no() "Is your name $*?" while true -n "Enter yes or no" read x case "$x" in y yes ) return 0;; n no ) return 1;; *) "Answer yes or no" esac "Original parameter are $*" if yes_or_no "$*" then "Hi $*, nice name" else "Never mind" 9 10 Recursive Function Does bash permit recursion? Yes, but it's so slow since it use big memory space. Running a script with recursion could possibly lock up your system! Recursive Function #!/bin/bash # fact.sh - Shell script to nd factorial of given command line arg factorial() local i=$1 local f # factorial() is called until the value of $f is returned and is it is <= 2 # This is called the recursion if [ $i -le 2 ]; then $i else f=$(( i - 1)) f=$(factorial $f) f=$(( f * i )) $f # display usage if [ $# -eq 0 ]; then "Usage: need a number for input" exit 1 # call factorial factorial $1 11 12 2

#!/bin/bash # recursive.sh # Demonstration of recursion. RECURSIONS=9 r_count=0 recurse () var="$1" # How many times to recurse. while [ "$var" -ge 0 ] "Recursion count = "$r_count" +-+ \$var = "$var"" (( var-- )); (( r_count++ )) recurse "$var recurse $RECURSIONS Break command Exit from a for, while or until loop SYNTAX break [n] If n is supplied, the nth enclosing loop is exited. n must be greater than or equal to 1. 13 14 Break Command Continue Command for myloop in 1 2 3 4 5 "$myloop" if [ "$myloop" -eq 3 ] then break Resume the next iteration of an enclosing for, while, until, or select loop. SYNTAX continue [n] If n is supplied, the execution of the nth enclosing loop is resumed. n must be greater than or equal to 1. 15 16 Continue Other Commands: eval for myloop in 1 2 3 4 5 if [ "$myloop" -eq 3 ] then continue # Skip rest of loop iteration. "$myloop" Indirect Variable References eval: allows you to evaluate argument foo=10 x=foo y=\$$x #it is same as y= $ $x $y $foo foo=10 x=foo eval y=\$$x $y 10 foo=10 x=foo # x=foo=100 eval \$$x 10 17 18 3

Other Commands: exit n exit command cause the script to exit with exit code. In shell programming, : exit with success exit 1 ~125 : exit with an error exit 126 : reserved code the le was not executable exit 127 : A command was not found exit 128 : a signal occurred Other Commands: export Set an environment variables. Mark each name to be passed to child processes in the environment 19 20 Other Commands: export Other Commands: expr #/bin/sh # export.sh: export variables to subscripts export gr1="happy" export gr2="new" export gr3="year"./import.sh./import1.sh. Evaluate expressions, evaluates an expression and writes the result on standard output. Syntax `expr expression...` # import.sh gr1, gr2, gr3 might be # imported from parent script "$gr1 $gr2 $gr3" # import1.sh: variable gr1 might be # imported from it's parent "$gr1 Birthday!" 21 22 # exprarith.sh: expr example with arithmetic operators a=5+3 "a is $a" "Arithmetic Operators" "--------------------" a=`expr 5 + 3` "now a = 5 + 3 = $a" a=`expr $a + 1` "a + 1 = $a" a=`expr 5 % 3` # modulo "5 mod 3 = $a" # exprlogic.sh: expr with Logical Operators # Returns 1 if true, 0 if false, # opposite of normal Bash convention. "Logical Operators" "-----------------" x=24 y=25 "x = $x and y = $y" "Compare with = operator" b=`expr $x = $y` "b = $b means x == y is false" "Compare with < operator" b= expr $x \< $y` "b = $b means x < y is true" "There are more operators such as <, <= >=,..." 23 24 4

# exprstring.sh : expr with string operators a=987abcd1234rtab "The string being operated upon is \"$a\"." # length: length of string b=`expr length $a` "Length of \"$a\" is $b." # index: position of rst character in substring that matches a character in string b=`expr index $a 2` "Numerical position of rst \"2\" in \"$a\" is \"$b\"." # substr: extract substring, starting position & length specied b=`expr substr $a 2 6` "Substring of \"$a\", starting at position 2,\ and 6 chars long is \"$b\"." # The default behavior of the 'match' operations is to search for the specied match at the # beginning of the string. uses Regular Expressions b=`expr match "$a" '[0-9]*'` # Numerical count. Number of digits at the beginning of \"$a\" is $b. b=`expr match "$a" '\([0-9]*\)'` # Note that escaped parentheses # == == + trigger substring match. "The digits at the beginning of \"$a\" are \"$b\"." Other Commands: printf Syntax printf Format strings, parameter list Format string : sequence of conversion specier (%d, %c, %s) Parameter list and conversion specier must be matched. Ex) printf "%d, %s, %c\\a" 2 "Hi" 'a' 25 26 Other Commands: printf Other Commands: set Escape Sequence in printf \b :backspace \f :form feed \n :Newline \r : carriage return \t : tap \v : vertical tap The set command sets the parameter variables for the shell script. Position parameter can change inside a script We can use the result of a command as a input to other commands 27 28 # script "set-test1.sh" # Invoke this script with three command line parameters, # for example, "./set-test one two three". Other Commands: set "Positional parameters before set \`uname -a\` :" "Command-line argument #1 = $1" "Command-line argument #2 = $2" "Command-line argument #3 = $3"./set-test.sh one two three $0=./set-test.sh $1=one $2=two $3=three set `uname -a` # Sets the positional parameters to the output # of the command `uname -a` $_ # last positional parameter # Flags set in script. "Positional parameters after set \`uname -a\` :" # $1, $2, $3, etc. reinitialized to result of `uname -a` i=1 for ARG in " $@ "; "Field " $i " of 'uname -a' = $ARG" let i++ set `uname -a` $1=Linux $2=claude $3=2.6.32.12-0.7-pae $4=#1 $5 = SMP.... $_=GNU/Linux 29 30 5

Other Commands: shift Other Commands: shift The shift command shift all positional parameter variable wn by one. $4 become $3, $3 become $2.. The previous value of $1 is discarded $0 (name of script) remains. # shft.sh: Using 'shift' to step through all the # positional parameters # need invoke shft.sh merry Christmas and happy new year "arguments before shift "$*"" until [ -z "$1" ] # Until all parameters used up... "$* " shift 31 32 6