Bash shell programming Part II – Control statements Deniz Savas and Michael Griffiths 2005-2012 Corporate Information and Computing Services The University.

Slides:



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

CIS 240 Introduction to UNIX Instructor: Sue Sampson.
Linux Shell Script. Shell script The first line is used to specify shell program #!/bin/sh Variables variable=“text” variable=0 variable=`program arguments`
Introduction to Unix – CS 21 Lecture 11. Lecture Overview Shell Programming Variable Discussion Command line parameters Arithmetic Discussion Control.
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.
CS 497C – Introduction to UNIX Lecture 33: - Shell Programming Chin-Chih Chang
Introduction to Unix (CA263) Decisions, Decisions By Tariq Ibn Aziz Dammam Community College.
CIS 240 Introduction to UNIX Instructor: Sue Sampson.
Further Shell Scripting Michael Griffiths Corporate Information and Computing Services The University of Sheffield
Shell Programming 1. Understanding Unix shell programming language: A. It has features of high-level languages. B. Convenient to do the programming. C.
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.
Lab 8 Shell Script Reference:
Shell Control Structures CSE 2031 Fall August 2015.
Shell Programming, or Scripting Shirley Moore CPS 5401 Fall August 29,
Agenda Control Flow Statements Purpose test statement if / elif / else Statements for loops while vs. until statements case statement break vs. continue.
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.
The if construct The general format of the if command is: Every command has exit status If the exit status is zero, then the commands that follow between.
Bash shell programming Part II – Control statements Deniz Savas and Michael Griffiths November 2005 Corporate Information and Computing Services The University.
Linux+ Guide to Linux Certification, Third Edition
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)
1 © 2001 John Urrutia. All rights reserved. Chapter 10 using the Bourne Again 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.
Chapter 10: BASH Shell Scripting Fun with fi. In this chapter … Control structures File descriptors Variables.
Shells. Variables MESSAGE="HELLO WORLD" echo $MESSAGE MESSAGE="HELLO WORLD $LOGNAME" echo $MESSAGE MESSAGE="HELLO WORLD $USER" echo $MESSAGE.
(A Very Short) Introduction to Shell Scripts CSCI N321 – System and Network Administration Copyright © 2000, 2003 by Scott Orr and the Trustees of Indiana.
©Colin Jamison 2004 Shell scripting in Linux Colin Jamison.
Xuan Guo Chapter 5 The Bourne Shell Graham Glass and King Ables, UNIX for Programmers and Users, Third Edition, Pearson Prentice Hall, Notes by Michael.
CISC3130, Spring 2011 Dr. Zhang 1 Bash Programming Review.
1 Lecture 9 Shell Programming – Command substitution Regular expressions and grep Use of exit, for loop and expr commands COP 3353 Introduction to UNIX.
Shell Script2 Reference: Linux Shell Scripting Tutorial v1.05r3 A Beginner's handbook
CISC3130 Spring 2013 Fordham Univ. 1 Bash Scripting: control structures.
Shell Programming Features “Full” programming language “Full” programming language Conditional statements Conditional statements Arithmetic, String, File,
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)
UNIX Shell Script (2) Dr. Tran, Van Hoai Faculty of Computer Science and Engineering HCMC Uni. of Technology
Flow Control. The order in which commands execute in a shell script is called the flow of the script. When you change the commands that execute based.
Sed. Class Issues vSphere Issues – root only until lab 3.
Lab 8 Shell Script Reference: Linux Shell Scripting Tutorial v1.05r3 A Beginner's handbook
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.
Shell script – part 2 CS 302. Special shell variable $0.. $9  Positional parameters or command line arguments  For example, a script myscript take 2.
If condition1 then statements elif condition2 more statements […] else even more statements fi.
Group, group, group One after the other: cmd1 ; cmd2 One or both: cmd1 && cmd2 Only one of them: cmd1 || cmd2 Cuddling (there):( cmd1 ; cmd2 ) Cuddling.
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]
Chapter 5 The Bourne Shell Graham Glass and King Ables, UNIX for Programmers and Users, Third Edition, Pearson Prentice Hall, Notes by Michael Weeks.
1 UNIX Operating Systems II Part 2: Shell Scripting Instructor: Stan Isaacs.
Bash shell programming Part II – Control statements Deniz Savas and Michael Griffiths Corporate Information and Computing Services The University.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
 Prepared by: Eng. Maryam Adel Abdel-Hady
Linux Administration Working with the BASH Shell.
1 Lecture 8 Shell Programming – Control Constructs COP 3353 Introduction to UNIX.
Chapters 13 and 14 in Quigley's "UNIX Shells by Example"
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.
Bash Shell Scripting 10 Second Guide.
CSC 352– Unix Programming, Spring 2016, Final Exam Guide
Agenda Bash Shell Scripting – Part II Logic statements Loop statements
CSC 352– Unix Programming, Fall 2012
Lecture 9 Shell Programming – Command substitution
Agenda Control Flow Statements Purpose test statement
Command Substitution Command substitution is the mechanism by which the shell performs a given set of commands and then substitutes their output in the.
Copyright © – Curt Hill Bash Flow of Control Copyright © – Curt Hill.
Presented by, Mr. Satish Pise
CSC 352– Unix Programming, Fall, 2011
Introduction to Bash Programming, part 3
Review.
Presentation transcript:

Bash shell programming Part II – Control statements Deniz Savas and Michael Griffiths Corporate Information and Computing Services The University of Sheffield

Topics covered Control Structures –If constructs –For loops –While … do & Until … do loops –Break & Continue commands –Case constructs –Select constructs Functions

Conditional Statements (if constructs ) The most general form of the if construct is; if command executes successfully then execute command elif this command executes successfully then execute this command and execute this command else execute default command fi Note that elif and/or else clauses can be omitted.

examples BASIC EXAMPLE: if date | grep “Fri” then echo “It’s Friday!” fi FULL EXAMPLE: if [ “$1” == “Monday” ] then echo “The typed argument is Monday.” elif [ “$1” == “Tuesday” ] then echo “Typed argument is Tuesday” else echo “Typed argument is neither Monday nor Tuesday” fi Note1 : = or == will both work in the test but == is better for readability. Note2: There must be spaces surrounding = or ==

string comparisons used with test or [[ ]] which is an alias for test and also [ ] which is another acceptable syntax string1 = string2 True if strings are identical String1 == string2 … ditto …. string1 !=string2 True if strings are not identical string Return 0 exit status (=true) if string is not null -n string Return 0 exit status (=true) if string is not null -z string Return 0 exit status (=true) if string is null IMPORTANT NOTE: [ and ] must be written separated by spaces on each side. [[ and ]] must not have a space in the middle.

Arithmetic comparison operations used with test and [ ] constructs int1 –eq int2Test identity int1 –ne int2Test inequality int1 –lt int2Less than int1 –gt int2Greater than int1 –le int2Less than or equal int1 –ge int2Greater than or equal

Combining tests using logical operators || (or) and && (and) Syntax: if cond1 && cond2 || cond3 … An alternative form is to use a compound statement using the –a and –o keywords, i.e. if cond1 –a cond22 –o cond3 … Where cond1,2,3.. Are either commands returning a a value or test conditions of the form [ ] or test … Examples: if date | grep “Fri” && `date +’%H’` -gt 17 then echo “It’s Friday, it’s hometime!!!” fi if [ “$a” –lt 0 –o “$a” –gt 100 ] # note the spaces around ] and [ then echo “ limits exceeded” fi Important note: If you like to have a NULL if clause or else clause put a : in one line. : implies a statement that does nothing.

A cunning way of using compound logical statements || and && conditions can be used to control the execution or otherwise of a command according to the outcome of an earlier command. In a compound test such as command1 && command2 command2 will only be executed if command1’s return-code was SUCCESS ( i.e. 0). On the other-hand in the compound statement command1||command2 command2 will only execute if command 1 FAILED ( i.e have a non-zero return code. See $?) Even more sophisticated control structures can be formed by multiple uses of these conditionals. Example : command1&&command2&&command3||command4 ( who | grep ‘fred’ ) && ( echo “Hello Freddie” | write fred ) || echo ‘No fred!’ The above command will send a message to user named fred only if he is logged in.

File enquiry operations -d fileTest if file is a directory -f fileTest if file is not a directory -s fileTest if the file has non zero length -r fileTest if the file is readable -w fileTest if the file is writable -x fileTest if the file is executable -o fileTest if the file is owned by the user -e fileTest if the file exists -z fileTest if the file has zero length All these conditions return true if satisfied and false otherwise.

Loops Loop is a block of code that is repeated a number of times. The repeating is performed either a pre-determined number of times determined by - a list of items in the loop count ( for loops ) or - until a particular condition is satisfied ( while and until loops) To provide flexibility to the loop constructs there are also two statements namely break and continue are provided.

for loops Syntax: for arg in list do command(s)... done Where the value of the variable arg is set to the values provided in the list one at a time and the block of statements executed. This is repeated until the list is exhausted. Example: for i in do echo " $i times 5 is $(( $i * 5 )) " done

for loops c-like syntax Syntax: for (( index=start ; test ; increment )) do : done EXAMPLE : for (( i=1 ; i <= maxfiles ; i++ )) do cat file${i} done for (( jj=20 ; jj >= 0 ; jj = jj -2 )) do echo $jj done

more on for loops A common trick is to assign to a local variable a list of Items and use that variable as a list driving the for loop. Example: files=`ls` for fil in $files do backfil="${fil}.back" if [ -f $fil ] && ! [ -e $backfil ] then echo " taking a backup copy of $fil“ cp -rp $fil $backfil fi done

while loops Syntax: while this_command_execute_successfully do : done EXAMPLE: while test "$i" -gt 0 # can also be coded as while [ $i > 0 ] do i=`expr $i - 1` done

while loops Example: while who > $tmpfile grep “$friend” $tmpfile > /dev/null do … commands.. done This loop will repeat until there are no jobs running for the user specified by the variable $friend.

until loops The syntax and usage is almost identical to the while- loops. Except that the block is executed until the test condition is satisfied, which is the opposite of the effect of test condition in while loops. Note: You can think of until as equivalent to not_while Syntax: until test do : done

break and continue statements These two statements are associated with the for, while and until loops and provide mechanisms for the abrupt exiting or incrementing of a loop. The break statement will exit a loop and the execution will continue following the done statement signifying the lexical extent of the loop. On the other hand the continue statement will terminate the current particular iteration and send the control back to the loop control test statement at the lexical beginning of the loop to tackle the next item on the list.

While, break and continue exercises Exercises. Study the script named limits9 in the course examples directory. Re-write it using if-else construct so as to remove the continue statement. Improve it further to eliminate the break statement.

(selection from a number of possibilities) Case statements The case structure compares a string ‘usually contained in a variable’ to one or more patterns and executes a block of code associated with the matching pattern. Matching-tests start with the first pattern and the subsequent patterns are tested only if no match is not found so far. case argument in pattern1 ) execute this command and this and this;; pattern2 ) execute this command and this and this;; esac Note : Pattern can be pattern1 | pattern2 | pattern3 … so on to imply the same block for different patterns.

Case construct example case "$1" in * ”.txt ”, *. ” doc ” ) ls "$1" mv "$1 “ txt echo "$1 moved to txt directory";; *".tmp") ls "$1" mv "$1 “ tmp echo "$1 moved to tmp directory";; * ) echo “ not a text file or temporary file “ ;; esac

Case constructs The following patterns have special meanings ?) Matches a string with exactly one character. [[:lower:]] ) or [a-z] ) matches any lowercase letter [[:upper:]] ) or [A-Z] ) matches any uppercase letter [0-9] ) matches any digit *) matches everything !!! The last pattern can be used to mean ‘anything-else’ And must be the last pattern on the list.

select constructs This construct is devised for menu generation. A list of words representing the allowed choices is presented to the user with each word preceeded by a number. The user is then invited to enter a number to identify the choice. Following user entry a block of code is then executed where actions can be taken depending on the choice.

Select construct select word in list do : done

An example of using select prefer=‘vegetarian vegan no_nuts halal kosher no_gluton quit’ select type in $prefer ; do case $type in “veg”* ) food=1 ; break ;; “halal”|”kosher” ) food=2 ; break ;; “no_nuts” ) food=3 ; break ;; “no_gluton” ) food=3 ; break ;; “quit” ) food=0 ; break;; esac done

Functions Functions are a way of grouping together commands so that they can later be executed via a single reference to their name. If the same set of instructions have to be repeated in more than one part of the code, this will save a lot of coding and also reduce possibility of typing errors. functionname() { block of commands } Advise: Put both curly brackets on a line on their own as shown here to avoid possible errors.

Functions Functions are like mini-scripts. But they run in the same shell environment as the script that contains it. Therefore all the locally declared variables in a shell script are also accessible and available in the functions it contains. However, the positional ‘command-line’ parameters passed to a script are not available to its containing functions. This is because the functions can take on their own positional parameters as they are invoked within the script. So, if you want to use the positional parameters of a script in a function within the script just pass them as parameters: Example: myinfunction $* or myinfunction $3 $1 … Use functions for use re-usability and readability

References: Follow the links from the research computing pages at Sheffield University to various documentation on shell script programming