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.

Slides:



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

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
Bash, part 2 Prof. Chris GauthierDickey COMP Unix Tools.
The Bourne Shell 吳 瑞 麟 National Cheng Kung University, Computer and Network Center.
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.
Guide To UNIX Using Linux Third Edition
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.
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.
8 Shell Programming Mauro Jaskelioff. Introduction Environment variables –How to use and assign them –Your PATH variable Introduction to shell programming.
An Introduction to Unix Shell Scripting
Shell Scripting Todd Kelley CST8207 – Todd Kelley1.
Shell Script Programming. 2 Using UNIX Shell Scripts Unlike high-level language programs, shell scripts do not have to be converted into machine language.
Introduction to Linux OS (IV) AUBG ICoSCIS Team Prof. Volin Karagiozov March, 09 – 10, 2013 SWU, Blagoevgrad.
Linux+ Guide to Linux Certification, Third Edition
CMPSC 60: Week 6 Discussion Originally Created By: Jason Wither Updated and Modified By: Ryan Dixon University of California Santa Barbara.
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.
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.
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.
(A Very Short) Introduction to Shell Scripts CSCI N321 – System and Network Administration Copyright © 2000, 2003 by Scott Orr and the Trustees of Indiana.
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.
©Colin Jamison 2004 Shell scripting in Linux Colin Jamison.
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.
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.
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 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.
 Prepared by: Eng. Maryam Adel Abdel-Hady
1 Lecture 8 Shell Programming – Control Constructs COP 3353 Introduction to UNIX.
Chapters 13 and 14 in Quigley's "UNIX Shells by Example"
ULI101 Week 10. Lesson Overview ● Shell Start-up and Configuration Files ● Shell History ● Alias Statement ● Shell Variables ● Introduction to Shell Scripting.
Bash Scripting CIRC Summer School 2016 Baowei Liu CIRC Summer School 2016 Baowei Liu.
Bash Shell Scripting 10 Second Guide.
CIRC Winter Boot Camp 2017 Baowei Liu
Department of Computer Engineering
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
Shell Scripting March 1st, 2004 Class Meeting 7.
CIRC Summer School 2017 Baowei Liu
Lecture 9 Shell Programming – Command substitution
CSE 303 Concepts and Tools for Software Development
Agenda Control Flow Statements Purpose test statement
Pepper (Help from Dr. Robert Siegfried)
LING 408/508: Computational Techniques for Linguists
PHP.
CSE 303 Concepts and Tools for Software Development
Linux Shell Script Programming
Shell Control Structures
Chapter 5 The Bourne Shell
CSC 352– Unix Programming, Fall, 2011
Shell Control Structures
Introduction to Bash Programming, part 3
Bash Scripting CS 580U - Fall 2018.
Basic shell scripting CS 2204 Class meeting 7
Presentation transcript:

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 shell scripts But BASH scripting features make scripting in bash more like programming in a traditional language

Uses Most of the linux SysV INIT run time environment is established through BASH scripts –Service start/stop scripts for example Simple scripts can be written to run a command with preset parameters –du -x -h --max-depth=${1:-1} Fairly simple scripts could, for example, send a custom to a file of addresses More complex scripts can perform perl like functions

Language Features A useful programming language has to have: –Variables to contain data –Literals Character Numeric Boolean –An if statement –A looping construct –Subroutines –A useful set of basic operations

BASH Variables Often called environment variables Many built in variables like $PATH are useful at the command line Some of the built in variables are particularly useful in scripts –$LINENO contains the line number of the script line being executed –Useful for debugging Scripts (or users) can create their own variables

Variable Names Best to stick to Perl rules –Letters numbers and underscore –Start with letter Note: variables names do not start with $ $ is an operator that substitutes the value of the variable into the command in place of the name X=1 echo $X displays the value 1 echo X displays the name X

Variable Types All BASH variables are character variables But if all of the contents are digits you can perform numeric operations If any of the characters are not digits BASH treats it as 0 (zero) in numeric operations

Variable Scope Every process has an Environment (a memory area) containing environment variables, and these variables are also available to the process's child processes Variables created in a script are in the script's memory space (not the process's environment) The export command exports the variable to the script's environment making it available to sub-processes created by the script Variables created in a code block or function may be local to the code block or function –Like perl private variables (my $variables)

Creating Variables name=value –Creates variable called “name” –Assigns the value “value” let a=$b+1 –Creates “a” –Evaluates numerical expression and assigns to “a” export a=value –Creates and exports “a”

Using Variables Usually we want the value of the variable inserted in the command in place of the name a=“Hello World” echo $a –Same as echo “Hello World” $a is a short form of ${a} Variables occasionally appear inside braces, with the $ prefix before the opening brace

Parameters Parameters passed to a script on the command line appear as variables inside the script $1 provides the value of the first parameter $2 … $9 provide the next 8 parameters $0 contains the name of the script ${11} is the eleventh parameter $# is the number of parameters $? = return value of last command $$ = PID of the script

Literals An unquoted string with no white space is a string literal h=hello w=world echo $h “ “ $w Strings containing white space must be quoted phrase=”hello world” echo $phrase

Quotes Variables within double quotes are interpolated –As in perl Variables within single quotes are not Strings in backticks are evaluated as a bash command and the output returned dir=`pwd` echo $dir –Prints current directory

Numeric Literals Numeric literals in a numeric expression are treated as numbers a=$((20 + 5)) echo $a –Displays 25 declare -i a –Makes a an integer –Values assigned to it are treated as numbers –Non-numeric strings are evaluated as 0

Boolean Values There is no special boolean data type In if statements and elsewhere 0 is treated as true if [ $? ] ; then echo 'last command successful' ; fi Note –“[“ is a command meaning “test” –Could have written if test $? –“;” is a statement separator –So is newline

If Statement General syntax: if command1 then command list else command list fi In this form –Newline terminates command1 –else and fi terminate the command lists

Another Form of if if command ; then command ; fi ';' teminates commands instead of newline Useful to run an if statement on the command line

If condition In the general format the condition of the if statement is a command If the return from the command is 0 then the condition is true “test” statement, or its synonym [ can be used to evaluate a boolean expression if [ $? ]; then echo “last command worked”; fi Note: whitespace is required after [

Some Boolean Constructs if [ $a = $b ] –Also == != \ For strings –Or -eq -ne -lt -gt -le -ge For numeric comparison if (( $a > $b )) –Or >= < <= For numeric comparison Note: (( 0 )) is false, (( 1 )) is true

File Tests if [ -e filename ] –File exists Also -d –File is a directory -s –Not size zero -r (or w or x) –Has read permission (or write or execute)

Some More Tests if [ -z “$a” ] –True if $a is null If [ -n “$a” ] –True if $a is not null Why the “ around $a ? –$a inserts the value of the variable a into the command –If $a is null then nothing is inserted and the command without quotes becomes: if [ -z ] –Rather than if [ -z “” ]

Boolean Operators Between tests: ! = not && = and (also -a) || = or (also -o) If [ ! -e file1 ] && [ -e file2] Can also be written If [ ! -e file1 -a -e file2]

[ and [[ [ is a built in command –Runs as part of the BASH executable [[ is an external command –Runs as a separate process [[ is more sophisticated (larger program) Sometimes behaves differently For example –if [[ -e file1 && -e file2 ]] –Is OK

Looping with for for argument in list do commands done Argument is a variable name Takes on value of each item in the list and then commands are executed List can be literals, variables, or an operator that generates a list for file in * ; do echo $file; done

Another for loop for (( expr1 ; expr2 ; expr3 )) do commands done Numeric expr1 is evaluated Expr2 is evaluated and if non-zero commands are executed Then expr3 is evaluated Like the equivalent perl loop

Looping with While and Until while [ condition ] do commands done [ is optional Can use [[ for fancier test Often used to read through a file

Reading a File with While read x –takes the next value from standard input assigns it to the variable x and returns 0 (true) as long as there is a value cat filename | script.sh –Pipes the records from filename into standard input of script.sh The following script would just print the records cat filename | ( while read record; do echo $record done )

User Input In the previous example, the contents of a file was piped to standard input of a sub-process Usually standard input is the keyboard, so read reads input from the user echo -n “Enter your selection: “ read choice echo “You entered $choice”

Loop Control break –Breaks out of a loop –Like the “last” statement in perl continue –Jumps to the next iteration of the loop –Like the “next” statement in perl Useful in forever loop while [ 0 ]

Case Statement case expression in pattern-list ) command ;; pattern-list) … ;; esac

Case (cont.) Expression can be any expression, usually a variable Value of the expression is matched to the patterns If it matches the commands are run “)” terminates the pattern list –Patterns separated by | “;;” terminates the command list esac terminates the entire structure and last command list

Patterns Are the same patterns used as wild cards in file names and elsewhere E matches the character E [Ee] matches upper or lower e [0-9] matches a range [digit] matches a digit * matches any string ? matches any single character

Parameter Expansion ‘$’ character introduces parameter expansion, command substitution, or arithmetic expansion Expansion means inserting the value of an expression into the command line ${VarName} inserts the value of VarName into the command line Can be written $VarName $(Command) inserts the output of Command into the command line Same as `Command`

Special Expansions ${var:-expression} –If var unset or null, return expression, else var ${var:=expression} –Also sets var = expression ${var:offset:length} returns substring ${#var} returns length of var Lots more

Comments The # character indicates that all following text is treated as a comment Must be the first character of a word –Basically means that it follows whitespace ls * # lists filenames in current directory –# starts a comment echo ${#Var} –Echos length of Var –# doesn't start a comment

Command Groups ( command list ) and { command list; } both treat the command list as a single command for the sake of redirection ( ) uses a separate subshell so variables in the group are local Example: ( command1; command2; command3 ) > filename – Sends output of all three commands to filename

Shell Functions Like perl functions, shell functions allow you to break a large program down into smaller modules When invoked, function runs in the same environment as the main program –Variables are global unless declared local Returns exit status of last command executed, or an integer specified in a return statement –Accessed through $? Must be defined before being called Can be passed parameters –$1 $2 etc

Shell Function Syntax function func_name { commands } Or func_name () { commands }

Invoking the Function Shell functions are invoked just like any other BASH command my_function string1 string2 if [ $? ] ; then –Function was successful string1 becomes the value of $1 inside function Can use $# etc inside function

Getting Help The man command prints a manual page for a command and is the recommended way of getting help Works only for external commands –Commands implemented via a separate executable file Built in commands are part of the bash executable and don't always have separate man pages man BASH has help for built ins but is tedious

Other Sources of Help The info command produces structured help that functions a little like HTML –OK if you learn to use it –Has been in unix since before HTML It is useful to find an online source of man pages that is authoritative A list is available here: Google results can be good sometimes, not always. Find a source you trust and bookmark it.

Running a BASH Script Save your commands in a text file –Name can be anything, but avoid using the name of an existing shell command –Extension can be anything but.sh is conventional –Some editors syntax highlight based on that extension First line should be: #!/bin/sh File needs to be executable –chmod +x file.sh Put in path, or provide fully qualified name./file.sh to run from current directory

References –On-line man pages ef.html#Bash-Builtinshttp:// ef.html#Bash-Builtins –Authoritative reference for BASH –Various guides, HTML on-line or dl, PDF –Advanced Bash-Scripting Guide is my favorite Appendix B is really useful –Bash Guide for Beginners seems good