CISC3130, Spring 2011 Dr. Zhang 1 Bash Programming Review.

Slides:



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

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.
CS 497C – Introduction to UNIX Lecture 33: - Shell Programming Chin-Chih Chang
Information Networking Security and Assurance Lab National Chung Cheng University 1 if condition Condition is defined as: "Condition is nothing but comparison.
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.
Shell Control Structures CSE 2031 Fall August 2015.
Shell Programming, or Scripting Shirley Moore CPS 5401 Fall August 29,
CISC3130, Spring 2013 Dr. Zhang 1 Bash Scripting: Advanced Topics.
Advanced Shell Programming. 2 Objectives Use techniques to ensure a script is employing the correct shell Set the default shell Configure Bash login and.
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 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.
Linux Shell Programming Tutorial 3 ENGR 3950U / CSCI 3020U Operating Systems Instructor: Dr. Kamran Sartipi.
Bash shell programming Part II – Control statements Deniz Savas and Michael Griffiths November 2005 Corporate Information and Computing Services The University.
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 Bash Programming Ellen Zhang. Previous three classes What have we learnt so far ?
Linux+ Guide to Linux Certification, Third Edition
UNIX Shell Script (1) Dr. Tran, Van Hoai Faculty of Computer Science and Engineering HCMC Uni. of Technology
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.
#!/bin/sh echo Hello World cat Firstshellscript.sh Firstshellscript.sh.
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)
Bash shell programming Part II – Control statements Deniz Savas and Michael Griffiths Corporate Information and Computing Services The University.
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.
Writing Scripts Hadi Otrok COEN 346.
©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.
1 Lecture 9 Shell Programming – Command substitution Regular expressions and grep Use of exit, for loop and expr commands COP 3353 Introduction to UNIX.
CSCI 330 UNIX and Network Programming Unit IX: Shell Scripts.
CISC3130 Spring 2013 Fordham Univ. 1 Bash Scripting: control structures.
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.
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.
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]
Compunet Corporation Introduction to Unix (CA263) Round and Round By Tariq Ibn Aziz Dammam Community College.
Chapter 5 The Bourne Shell Graham Glass and King Ables, UNIX for Programmers and Users, Third Edition, Pearson Prentice Hall, Notes by Michael Weeks.
2 nd Intro to Shell Scripting. Dates for Last Week of Class Homework 7 – Due Tuesday 5/1 by midnight Labs 7 & 8 or late ones – 8 is extra credit – Due.
By Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
1 UNIX Operating Systems II Part 2: Shell Scripting Instructor: Stan Isaacs.
 Prepared by: Eng. Maryam Adel Abdel-Hady
Linux Administration Working with the BASH Shell.
Shell Control Structures CSE 2031 Fall June 2016.
1 Lecture 8 Shell Programming – Control Constructs COP 3353 Introduction to UNIX.
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
What is Bash Shell Scripting?
Pepper (Help from Dr. Robert Siegfried)
Linux Shell Script Programming
Chapter 5 The Bourne Shell
CSC 352– Unix Programming, Fall, 2011
Shell Control Structures
CST8177 Scripting 2: What?.
Introduction to Bash Programming, part 3
Presentation transcript:

CISC3130, Spring 2011 Dr. Zhang 1 Bash Programming Review

Outline 2 Coding standard: how to get good grades in lab assignment Review of standard input/output/error How to redirect them ? Pipeline Review of bash scripting

Standard input/output/error 3 By default, link to keyboard and terminal window respectively Can be redirected to files Can be redirected to pipeline input can be redirected to reading end of a pipe output and error can be redirected to writing end of a pipe When a bash script’s input/output/error is redirected: E.g., headtail 3 10.bash_profile > output ls –l | headtail | wc –l input/output/error for every command in the script are redirected !

Save standard input if necessary 4 cat > stdinput ## save standard input to a file ## so that we can use as many times as we want wc –l stdinput grep PHONE stdinput

Redirection can be applied to loop 5 for i in `ls` do echo $i cat $i done > all_files Similar for <, |

Outline 6 Coding standard: how to get good grades in lab assignment Review of standard input/output/error How to redirect them ? Pipeline Review of bash scripting

Bash scripting: general hints 7 Use echo command to trace (like cout, printf in C/C++) Sometimes there are alternatives ways to do things, choose one and remember it: $(( …)), and $[ … ] [[ ]] for test Be careful about typo, shell wont complain variable not declared/assigned … The price of freedom A walk-through of basic bash scripting

Bash Scripting 8 Variables Environment variable: affect behavior of shell User defined variable: default type is string, can declare it to be other type Positional variables: used to pass command line arguments to bash script Variable assignment: x=10 ## assign value 10 to variable x, no space around = x=$x+1 ## add 1 to x’s value and assign to x PATH=$PATH:.:~/bin To refer to a variable’s value, precede variable name with $

A script that display positional variable 9 echo All arguments: $* echo Number of arguments: $# echo Script name: $0 echo argument 1: $1 echo argument 2: $2 for arg in $* do echo argument $arg done

demo 10 CISC3130]$./test tmpfile All arguments: tmpfile Number of arguments: 3 Script name:./test argument 1: 10 argument 2: 20 argument 10 argument 20 argument tmpfile

arithmetic operation 11 As variable’s default type is string, to perform arithmetic operation, use the following syntax $[$x+1] or $(($x+1)) For simpler syntax: declare variable to be numerical declare –i x x=$x*10+2 Above are for integer arithmetic operations only..

Command bc 12 An arbitrary precision calculator $ bc *10^ ^ sqrt(1000) 31 scale=4 sqrt(1000) quit An interactive calculator: * user input shown in normal font, * result shown in italics font Internal variable scale: * control the number of decimal points after decimal point

bc in command line/script 13 To evaluate an expression, simply send it using pipe to bc echo " " | bc Write a script that read a Fahrenheit degree from standard input, convert it to Celsius degree (up to 2 digits after decimal point): C=(F-32)*5/9 Base conversion, from base 10 (decimal) to base 16 (hexadecimal) echo "obase=16; ibase=10; 56" | bc

Test/Conditions 14 Any command or script, if it return 0, then test is successful if rm tmp.txt then echo file tmp.txt has been deleted else echo fail to remove file tmp.txt Fi Use ! to negate

Test Condition 15 Numerical comparisons -lt, -ne, -ge, … String comparision Pattern matching: using double brackets To test if first argument is “–” followed by a number: if [[ "$1" == -[0-9]* ]] then ….

AND/OR list construct 16 Statement1 && statement2 && statement3 && … Each statement is executed; if it returns true, next statement is executed…. Until finding first statement that returns false, or all statements return true Note: the statement can be any command, such as echo (which always return true) Statement1 || statement2 || statement3 || … Each statement is executed; if it returns false, next statement is executed…. Until finding first statement that returns true (the construct then return true), or all statements return false (the construct then returns false).

Check password: maximum 5 tries 17 tries=0; limit=5 while [ "$input" != "secret“ ] && [ $tries –lt $limit ] do echo "Enter your password" read input; tries=$(($tries+1)) done if [ $input= “secret” ] then echo "welcome!“ else echo “retry limit (5) reached” fi

Infinite loop 18 while [ 1 ] do echo -n "Enter your password" read input if [ $input = "secret" ] then break else echo -n "Try again... " fi done

Useful command : select loop 19 #!/bin/bash OPTIONS="Hello Quit“ select opt in $OPTIONS; do if [ "$opt" = "Quit" ] then echo done exit elif [ "$opt" = "Hello" ] then echo Hello World else echo bad option fi done Recall pick command ?

Next: 20 More advanced bash scripting Array Function Here document

Array 21 Bash provides one-dimensional array variables. There is no maximum limit on the size of an array, nor any requirement that members be indexed or assigned contiguously. Arrays are indexed using integers and are zero-based. Assign values to array: array=( one two three ) files=( "/etc/passwd" "/etc/group" "/etc/hosts" ) limits=( 10, 20, 26, 39, 48)

To Iterate Through Array Values 22 for i in do # do whatever on $i done #!/bin/bash # declare an array called array and define 3 vales array=( one two three ) for i in do echo $i done

Functions 23 One can define functions to increase modularity and readability of shell scripts More efficient than breaking large scripts into many smaller ones… Why ? foo() { Echo “in function foo” } echo “start script…” foo echo “end script …”

About functions 24 Need to be defined first, and then can be called Parameter passing #! /bin/bash calsum(){ echo `expr $1 + $2` } x=1;y=2; calsum $x $y

About functions 25 Result returning Through setting a variable Use return command Use echo command #! /bin/bash calsum(){ echo `expr $1 + $2` } x=1;y=2; calsum $x $y z=`calsum $x $y` calsum(){ z=`expr $1 + $2` } x=1;y=2; calsum $x $y echo z=$z

About functions 26 Local variable: its scope is within the function #! /bin/bash calsumsqr(){ local sum=`expr $1 + $2`; echo `expr $sum * $sum` } x=1;y=2; calsum $x $y z=`calsum $x $y`

Here document 27 A special way to pass input to a command: here document, i.e., from the shell script itself #!/bin/bash cat <<!FUNKY! Hello This is a here Document !FUNKY! Here document starts with <<, followed by a special string which is repeated at the end of the document. Note: the special string should be chosen to be rare one.

Here document:2 28 Benefits: store codes and data together, easier to maintain Example: 411 script grep “$*” << End Dial-a-joke Dial-a-prayer Dial santa End ~/Demo/Examples/411

A case study: bundle program (P 97) 29 Suppose a friend asks for copies of shell files in your bin directory $ cd /user/you/bin $ for i in *.sh > do > echo ===== This is file $i =============== > cat $i > done | mail Pipeline & input/output redirection can be applied to for, while, until loop.

Make it better ? 30 Construct a mail message that could automatically unpack itself, i.e., to generate the original files packed inside A shell script contains instructions for unpacking, and files themselves Use here document mechanism Generate this shell script using another script

Bundle script 31 #!/bin/bash echo ‘# To unbundle, bash this file’ for i do echo “echo $i 1>&2” echo “cat >$i <<‘End of $i’” cat $i echo “End of $i” done ~/Examples/writescript bundle.sh

An example bundle file 32 Try it out:./bundle.sh bundle.sh 411 > junk Inside junk:

Inside junk file 33 #To unbundle, bash this file echo bundle.sh 1>&2 cat >bundle.sh <<'End of bundle.sh' #!/bin/bash echo '#To unbundle, bash this file' for i in ## or for i do echo "echo $i 1>&2" echo "cat >$i <<'End of $i'" cat $i echo "End of $i" done end of bundle.sh echo 411 1>&2 cat >411 <<'End of 411' grep "$*" <<End dial-a-joke dial-a-prayer dial santa today is `date` end end of 411