CIS 191: Linux and Unix Class 3 February 11 th, 2015.

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
CSc 352 Shell Scripts Saumya Debray Dept. of Computer Science
Guide To UNIX Using Linux Third Edition
Introduction to Unix (CA263) Introduction to Shell Script Programming By Tariq Ibn Aziz.
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 Script Examples.
CTEC 1863 – Operating Systems Shell Scripting. CTEC F2 Overview How shell works Command line parameters –Shift command Variables –Including.
Shell Programming, or Scripting Shirley Moore CPS 5401 Fall August 29,
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 Bash Programming Ellen Zhang. Previous three classes What have we learnt so far ?
Linux+ Guide to Linux Certification, Third Edition
Linux Operations and Administration
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.
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.
Beyond sh Not everyone is as fond of UNIX as most other people. The tutorial talks about the dark side of UNIX.
CSC 352– Unix Programming, Spring 2015 March 2015 Shell Programming (Highlights only)
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.
LIN Unix Lecture 5 Unix Shell Scripts. LIN Command Coordination ; && || command1 ; command2 Interpretation: Do command 1. Then do command.
©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.
Chapter Six Introduction to Shell Script Programming.
CS252: Systems Programming Ninghui Li Slides by Prof. Gustavo Rodriguez-Rivera Topic 7: Unix Tools and Shell Scripts.
Agenda Positional Parameters / Continued... Command Substitution Bourne Shell / Bash Shell / Korn Shell Mathematical Expressions Bourne Shell / Bash Shell.
Chapter 5: The Shell The Man in the Middle. In this chapter … The command line Input, output, and redirection Process management Wildcards and expansion.
CIS 191: Linux and Unix Class 3 September 23rd, 2015.
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.
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.
1 UNIX Operating Systems II Part 2: Shell Scripting Instructor: Stan Isaacs.
Linux Administration Working with the BASH Shell.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
INTRODUCTION TO SHELL SCRIPTING By Byamukama Frank
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.
Department of Computer Engineering
Agenda Bash Shell Scripting – Part II Logic statements Loop statements
CSC 352– Unix Programming, Fall 2012
Lecture 9 Shell Programming – Command substitution
Shell Programming (ch 10)
CSE 303 Concepts and Tools for Software Development
What is Bash Shell Scripting?
LING 408/508: Computational Techniques for Linguists
CSE 303 Concepts and Tools for Software Development
Linux Shell Script Programming
CSE 303 Concepts and Tools for Software Development
Shell Control Structures
CSC 352– Unix Programming, Fall, 2011
Shell Control Structures
Introduction to Bash Programming, part 3
Presentation transcript:

CIS 191: Linux and Unix Class 3 February 11 th, 2015

Aside: Vim or Emacs in your shell! Add one of the following to your.bashrc to have basic editor commands added to your shell session!!! – set –o vi – set –o emacs

Outline Review of Last Week Branching Constructs Loop Constructs More Shell Scripting Constructs

Shell Constructs in Brief | - Pipes, 2> - Redirections $( ), ` ` - Command Substitution ;, &&, || - Command Lists & - Run in background

Variables var=str assigns the text str to the variable var $var is replaced with the text stored in var echo $var prints the text in var Variables that have not been set are replaced with the empty string – Kind of like the null value in Java – So, echo $notset will print a blank line

Filename Completion Recall Wildcards – * will match any string of text (except for hidden files) – ? will match any single character (again, except hidden files) Some new stuff – [chars] matches any character enclosed [a-z] matches the range of characters from a to z – {list} is expanded to a space-delimited term once for each item in the list Recall the scp command from homework 1 So, twenty-{one,two,three,four} is expanded to – twenty-one twenty-two twenty-three twenty-four

Note on notation From this point forward, single line shell interactions will still be preceded by a $, as before. – Input to the shell and resulting output will be on consecutive lines Longer pieces of shell scripting will be written in consolas, but not preceded by a $. – Output will be displayed separately

Expansions Save Keystrokes A simple way to list all files for i in *; do echo $i is a file done From now on, expect to see this * notation instead of $(ls). So, to copy all CIS191 lecture notes to their own directory, just do – $ mkdir CIS191 && cp cis191* CIS191

Outline Review of Last Week Branching Constructs Loop Constructs More Shell Scripting Constructs

The If statement if command then commands elif command then commands else commands fi xkcd.com/17

An If and test example! if [ $SHELL = /bin/bash ] then echo ‘You are using bash’ else echo ‘Your shell is not /bin/bash’ fi

We can inline these statements with ; Equivalently… (and this holds similarly for for loops and other like constructs) $ if [ $SHELL = /bin/bash ]; then echo ‘You are using bash’; else echo ‘Your shell is not /bin/bash’; fi This is bad form when writing your scripts to save and distribute or execute later or submit for a homework assignment! But it can be useful when writing a one liner in the command line (and you are not intending to save it)

test A simple test binary which is often found with if. Often, we’ll see test run via its alias, the [ ] operator – This is usually a shell command, not a program… (fyi) Note that all the following commands can be run by typing [ my arguments ] or test my arguments – It’s really just a matter of style – I’d recommend using the square braces in an if statement for syntactic sugar

A couple more test notes… You have to write the notation exactly as we showed it here! [-e file] IS NOT THE SAME as [ -e file ] – You must have the space separating the brackets and other text! Also, to reiterate, the brackets are just an alias for the test command. To test for file existence, you could also type – test –e file

If and Test example hours=$(date +%H) if [ $hours –lt 12 ]; then echo It is before noon. fi Note the semicolons before then in this usage case

Test Conditions (Strings) [ $str1 = $str2 ] => success if str1 is equal to str2 [ $str1 != $str2 ] => success if str1 is not equal to str2 [ -z $str ] => success if the string empty (null) [ -n $str ] => success if the string is nonempty (not null) [ $str1 success if str1 is less than str2 (alpha) [ $str2 > $str2 ] => success if str1 is greater than str2

Test Conditions (numbers) The following convert the strings m and n to numbers before doing tests on them [ $m –eq $n ] => success if m is equal to n [ $m –ne $n ] => success if m is not equal to n [ $m –lt $n ] => success if m is less than n [ $m – le $n ] => success if m is less than or equal to n [ $m –gt $n ] => success if m is greater than n [ $m –ge $n ] => success if m is greater than or equal to n

Test Conditions (files) [ -e filename ] => success if filename names a file [ -d dirname ] => success if dirname names a directory [ -r filename ] => success if filename names a file for which the current user has read permissions [ -o filename ] => success if filename names a file which the current user owns There are other options as well – Checking write/execute permissions, filetype, etc See test(1) man page for more details – man test

How do we define “true” and “false”? In bash, “true” is a success code And “false” is an error code A success code is always 0 – And anything else is an error…

Some standard exit codes 0 – normal (true) 1 – catchall for any general error 2 – wrong usage 126 – file is not executable 127 – file not found 128 – program killed by ^C

An example of using error codes Good for reporting errors if rm file; then echo Removal worked. else echo Removal failed. fi

If – diff edition #!/bin/sh #Say $1 is the username if diff $1/homework reference-answer; then response=‘Incorrect answer!’ else response=‘Correct answer!’ fi echo $response >> $1/grade.txt

If: grep edition Our old friend grep returns success or failure too… #!/bin/sh # Assume $1 is the username if grep ‘pants’ myfile.txt; then echo ‘Your file contains pants!’ else echo ‘Clothe your file please.’ fi

Outline Review of Last Week Branching Constructs Loop Constructs More Shell Scripting Constructs

For: A foreach construct Use for loops to repeat an iteration over a set of values The general form is as follows: for i in list do commands… done i is set to each of the items in list, in turn commands is a list of commands to execute

For: example for i in one two red blue do echo $i fish done The results are one fish two fish red fish blue fish

For – example for i in optimus; do echo $i: prime done

Internal Field Separator (IFS) This is how the shell knows how to split a string of text into a list which can be iterated through Make sure not to change this globally – Why might this be a bad idea? Change IFS locally only – Good for iterating through a comma-separated line, or a line separated by semicolons… (etc) – Save old value of IFS $ OLDIFS=$IFS $ IFS=‘,’ $ IFS=$OLDIFS

Useful: Debug Mode You can run any script with – $ bash –x script.sh to enter debug mode – This will show each command being run (after substitutions and aliases, and in a loop iteration

If, For, and Test: Better Together!! What does this do? for i in $(ls) do if [ -d $i ] echo $i is a directory fi done

If, For, and Test: Better Together!! What does this do? for i in $(ls) do if [ -d $i ] echo $i is a directory fi done It lists directories, but not other types of files (and adds some flavor text to boot)

While – Another way to Loop! The while loop repeats an action while a condition is true – Sound familiar? while condition do commands done

Until – do until a condition is satisfied The until loop repeats an action until a condition is satisfied until condition do commands done

Wait until a minute is finished while [ $(date +%S) != 00 ]; do sleep 1 done echo A new minute just started. or, equivalently until [ $(date +%S) == 00 ]; do sleep 1 done echo A new minute just started.

read – User input This command allows you to get user input for your scripts $ read x hey there $ echo $x – hey there $ read x y hey there $ echo $x and $y – hey and there

While + read You can use the read function in conjunction with a while loop for short hand (read returns a status code) – read returns success if it gets input, and gives an error code if it receives an EOF (^D) on a blank line. while read x do echo You input ${x}. done

So, to exit a while read loop… We have a couple of options We can kill the program – ^C, ^\ We can give read a zero-length string – ^D (EOF) on an empty line – Why won’t just pressing enter work? We can break out of the loop programmatically on some input

break and continue Basically the exact same functionality as in standard curly brace languages (c, java) break – If this command is encountered, then the script will exit the innermost loop continue – If this command is encountered, then the loop will stop execution of the loop body and skip to the next iteration of the loop

In example while read x; do if [ $x == 'quit' ]; then break elif [ $x == 'skip' ]; then continue fi echo You entered ${x}. done

Redirection and while read loops Consider the following while read line; do echo $line done < myfile.txt

Leveraging read’s break on newline Since read breaks on the newline, we can pipe the contents of any file we like into the while-read loop’s standard input – This provides a very convenient way to loop through the lines in a file…

Outline Review of Last Week Branching Constructs Loop Constructs More Shell Scripting Constructs

Arithmetic in Bash

As we discussed, the shell primarily operates on strings But if you’ve ever programmed anything ever, then you know that sometimes arithmetic is necessary… In bash, arithmetic is placed inside $(( )). For example – $ echo The UID after yours is $(($UID + 1)) – $ echo Six times nine is $((6 * 9))

Arithmetic Example Suppose you wanted to count the subdirectories using bash arithmetic count=0 for i in *; do if [ -d $i ]; then count=$(($count + 1)) fi done echo There are $count subdirectories.

Bash and floating point arithmetic Bash doesn’t do floating point arithmetic – Just does typical integer truncation if an expression would evaluate to a decimal point

Curly Braces for Dereferencing variables $ foo=herp $ echo ${foo} herp Considered to be good practice in all cases – Didn’t go into this last class for clarity… Also useful to expand variables when we want to append text to them without any whitespace… $ echo ${foo}derp herpderp

Bash arrays It’s possible to define arrays in bash, too! – Though they are more like maps or dictionaries than arrays $ myarr[1]=first $ myarr[2]=second $ myarr[me]=ohmy

Dereferencing arrays requires { } Unlike other variables, dereferencing an array requires the use of curly braces! $ echo ${myarr[1]} first $ echo ${myarr[1]}not${myarr[2]} firstnotsecond $ echo me${myarr[me]} meohmy $ echo $myarr[me] ohmy[me] (what?? – remember to use curly braces!)

Arrays are not backwards compatible! It’s important to note that POSIX compliant scripts should not make use of the array notation! Older interpreters such as sh and dash do not support arrays or the array syntax In general, if you are using arrays, you should consider writing the script in another language… Including them for completion more than as advice

Script Arguments Your scripts can accept CLI arguments too! – $1 is the first parameter to a script – $2 is the second parameter to a script and so on and so on… – $0 is the name of the script (the filename) – is the list of arguments (as a bash array) – $* is also the list of arguments (as a space delimited string) – $# is the number of arguments passed to the script

shift operator for arguments Calling shift in a bash script will pop the first argument off the argument list, making $1=$2, $2=$3, and so on Another way to iterate through all input arguments! while [ $1 ]; do stuff shift done

Shell Functions You can place code that needs to be repeated in a function (just like in other programming languages) – Shell functions can be though of like sub-scripts – If you define a function in the current shell environment, then the shell will tab complete the function for you! name () { commands }

Shell Functions Can also be written in one line (like anything else in bash) – $ name() { commands; } Arguments to functions are retrieved the same way they are to scripts – So, $1 is the first argument, $# is the number of arguments…

What does this do? $ :() {: | :&}; :

Kaboom! $ () {: | :&}; : Well, “:” is a valid name in bash… so it’s basically just a function name. Let’s try replacing it with “bomb”. $ bomb() {bomb | bomb&}; bomb Does this make things any clearer?

Breakdown This statement defines a function, :, which runs itself in the background twice – Then we call that function This is the canonical bash fork bomb Don’t run this on Eniac. – They’ll know it was you. Don’t run it on your own computer either. You’ll need to restart it (or the virtual machine).