LIN 69321 Unix Lecture 5 Unix Shell Scripts. LIN 69322 Command Coordination ; && || command1 ; command2 Interpretation: Do command 1. Then do command.

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.
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.
Scripting Languages and C-Shell. What is a scripting language ? Script is a sequence of commands written as plain text and run by an interpreter (shell).
CSc 352 Shell Scripts Saumya Debray Dept. of Computer Science
Shell Scripts 4 A shell usually interprets a single line of input, but we can also create a file containing a number of lines of commands to be interpreted.
Shell Programming 1. Understanding Unix shell programming language: A. It has features of high-level languages. B. Convenient to do the programming. C.
Unix Shell Scripts. What are scripts ? Text files in certain format that are run by another program Examples: –Perl –Javascript –Shell scripts (we learn.
Bash Shell Scripting 10 Second Guide Common environment variables PATH - Sets the search path for any executable command. Similar to the PATH variable.
Using Unix Shell Scripts to Manage Large Data
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.
CS 141 Labs are mandatory. Attendance will be taken in each lab. Make account on moodle. Projects will be submitted via moodle.
Shell Control Structures CSE 2031 Fall August 2015.
COMP1070/2002/lec4/H.Melikian COMP1070 Lecture #5  Files and directories in UNIX  Various types of files  File attributes  Notion of pathname  Commands.
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.
8 Shell Programming Mauro Jaskelioff. Introduction Environment variables –How to use and assign them –Your PATH variable Introduction to shell programming.
Chapter 6: Shell Programming
An Introduction to Unix Shell Scripting
Writing C-shell scripts #!/bin/csh # Author: Ken Berman # Date: # Purpose: display command and parameters echo $0 echo $argv[*]
Shell Script Programming. 2 Using UNIX Shell Scripts Unlike high-level language programs, shell scripts do not have to be converted into machine language.
Additional UNIX Commands. 222 Lecture Overview  Multiple commands and job control  More useful UNIX utilities.
1 Shell Scripting (C shell) SungHo Maeung 10/27/2000 Tutorial section Computer Science Lab.
Lecture 4  C Shell Scripts(Chapter 10). Shell script/program  Shell script: a series of shell commands placed in an ASCII text file  Commands include.
Introduction to Bash Programming Ellen Zhang. Previous three classes What have we learnt so far ?
LINUX System : Lecture 6 Shell Programming
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.
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 Operating Systems Lecture 2 UNIX and Shell Scripts.
Lecture 24CS311 – Operating Systems 1 1 CS311 – Lecture 24 Outline Final Exam Study Guide Note: These lecture notes are not intended replace your notes.
Writing Scripts Hadi Otrok COEN 346.
©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.
Chapter Six Introduction to Shell Script Programming.
CSCI 330 UNIX and Network Programming Unit IX: Shell Scripts.
1 Unix/Linux commands and shell programming-Part 2 (Dr. Mohamed El Bachir Menai)
Sed. Class Issues vSphere Issues – root only until lab 3.
1 Writing Shell Scripts Professor Ching-Chi Hsu 1998 年 4 月.
Various 2. readonly readonly x=4 x=44 #this will give an error (like what in java?)
File Management commands cat Cat command cat cal.txt cat command displays the contents of a file here cal.txt on screen (or standard out).
Linux Tutorial Lesson Two *Getting Help in Linux *Data movement and manipulation *Relative and Absolute path *Processes Note: see chapter 1,2,3 from Linux.
1 UNIX Operating Systems II Part 2: Shell Scripting Instructor: Stan Isaacs.
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.
Chapters 13 and 14 in Quigley's "UNIX Shells by Example"
Shell Control Structures
Part 1: Basic Commands/Utilities
Some Linux Commands.
Shell Scripting March 1st, 2004 Class Meeting 7.
LINUX System : Lecture 5 (English-Only Lecture)
Lecture 9 Shell Programming – Command substitution
CSE 303 Concepts and Tools for Software Development
Using Linux Commands Lab 3.
UNIX Reference Sheets CSE 2031 Fall 2010.
Copyright © – Curt Hill Bash Flow of Control Copyright © – Curt Hill.
Shell Programming.
Linux Shell Script Programming
Shell Control Structures
Module 6 Working with Files and Directories
Shell Control Structures
Introduction to Bash Programming, part 3
Basic shell scripting CS 2204 Class meeting 7
Presentation transcript:

LIN Unix Lecture 5 Unix Shell Scripts

LIN Command Coordination ; && || command1 ; command2 Interpretation: Do command 1. Then do command 2 Description: The semicolon links two commands that are executed by the shell in simple sequential order. This means that csh will run the first command in the sequence, then once that command is finished, it will run the next command. Linking commands with semicolons is analogous to executing them as separate commands. That is, the command line below: % cd ~/public_html ; ls *.html is equivalent to this: % cd ~/public_html % ls *.html

LIN Command Coordination ; && || command1 && command2 Interpretation: Do command 2 only if command 1 executes successfully (and not otherwise). Description The double-ampersand links two commands as a very simple case of a conditional. This means that there is a condition under which command2 is executed: namely only if command1 executes successfully. This is only a little more complex than the semicolon operator. For example, giving a command like this: % clear && cal will attempt to run the clear command first. If and only if the clear command works (i.e., returns an exit status of 0), the shell will run the cal command. If the clear command does not work (i.e., returns a non-zero exit status), then the cal command is not even attempted.

LIN Command Coordination ; && || command1 || command2 Interpretation Do command 1 or command 2 (but not both). Description: || means something like "OR". The shell will attempt to execute command1 first. If and only if command1 fails (i.e., returns a non-zero exit status), the shell will run command2. If command1 exits cleanly, the shell does not even attempt running command2. For example, if you type something like this: % rm /etc/motd || echo "Sorry, can't remove file." The shell will attempt to remove the file /etc/motd first. If that works, then nothing else happens. However, if that command doesn't work for any reason (like maybe you don't have permission), the shell will run the echo command, and print the message Sorry, can't remove the file to the screen. Give it a shot to see what we're talking about.

LIN Shell Script File any collection of csh commands may be stored in a file, a shell script file csh can be invoked to execute the commands in that file the language used in that file is called shell script language Like other programming languages it has variables and flow control statements: e.g. if-then-else, while, for, goto.

LIN Invoking Shell Scripts DIRECT INTERPRETATION % csh filename [arg...] invokes the program csh to interpret the script contained in the file `filename'. INDIRECT INTERPRETATION we insert as the first line of the file #! /bin/csh (by default) Or use the information given when you execute the command % echo $SHELL /usr/local/bin/tcsh AND the file must be made executable using chmod

LIN A simple example: listfiles #! /usr/local/bin/tcsh echo "hello, $USER. I wish to list some files of yours" echo "listing files in the current directory, $PWD" ls # list files $USER and $PWD are standard variables defined by the csh and needn't be defined in the script the variables are expanded when the variable name is inside double quote: the shell sees the string $USER and replaces it with the variable's value then executes the command.

LIN Setting Variables Any programming language needs variables. You define a variable as follows: set X will set the variable X to have an empty list as its value and refer to it as follows: $X $X is used to denote the value of the variable X set X = dear

LIN A simple example: listfiles1 #! /usr/local/bin/tcsh set X = dear echo "hello, $X $USER. I wish to list some files of yours" echo "listing files in the current directory, $PWD" ls # list files $USER and $PWD are standard variables defined by the csh and needn't be defined in the script the variables are expanded when the variable name is inside double quote: the shell sees the string $USER and replaces it with the variable's value then executes the command.

LIN Command Arguments Most commands have arguments, and these are accessible via the shell variable $argv. The first parameter will be $argv[1], the second $argv[2], and so on. The number of such arguments is $#argv. Consider the following script file, named swap : #! /bin/csh set tmp = $argv[1] cp $argv[2] $argv[1] cp $tmp $argv[2] If you have files x and y, and type % swap x y then the new contents of x would be what is in y.

LIN Command Arguments Most commands have arguments, and these are accessible via the shell variable $argv. The first parameter will be $argv[1], the second $argv[2], and so on. The number of such arguments is $#argv. Consider the following script file, named swap : #! /usr/local/bin/tcsh set tmp = $argv[1] cp $argv[2] $argv[1] cp $tmp $argv[2] If you have files x and y, and type % swap x y then the new contents of x would be what is in y.

LIN Flow Control Statements Conditional If … then … endif Conditionals are commands which are executed only if a certain condition is true. Syntax of the if conditional: if ( expression ) then command endif If expression is true, then command is executed. If expression is false, command is not executed.

LIN Flow Control Statements Conditional If … then … endif # over checks if a number is greater than 100 if ( $1 > 100 ) then echo ”That’s a big number!” endif

LIN A note on Relational Operators ==equal to !=not equal to <less than >greater than <=less than or equal to >=greater than or equal to

LIN Flow Control Statements Conditional If expression is true, more than one command can be executed if ( expression ) then command1 # these commands are executed if expression is true command2... endif

LIN Flow Control Statements Conditional # over100add -- checks if a number is greater than 100, adds 1 to # it and then subtracts 2 from it. if ( $1 > 100 ) then echo ”That’s a big number!” echo "$1 is a big number." echo ”But `expr $1 + 1` is even bigger.” echo `expr $1 - 2` endif Recall: The backquotes ` around a command signify COMMAND SUBSTITUTION: The output from the backquoted command is included within the command line for another command.

LIN Flow Control Statements Conditional an if statement can also have a set of commands which run if expression is false, using the else command: if ( expression ) then command1 # these commands are executed if expression is true command2... else command11 # these commands are executed if expression is false command12... endif

LIN Flow Control Statements Conditional #! /bin/csh # string_check -- checks two strings # first, make sure the user typed in two arguments following the command if ( $# != 2 ) then echo "This script needs exactly two (2) arguments." echo "Exiting...(annoyed)" exit 666 endif # now, compare them if ( $1 == $2 ) then echo "$1 and $2 are the same, aren't they?" else echo "$1 and $2 are different, aren't they?" endif

LIN Flow Control Statements foreach ‘loop’ The syntax of foreach loop construct is foreach var ( wordlist ) command(s) end The command(s) is executed once for each “word” (or item) in the wordlist, and each time the variable var will contain the value of that word.

LIN Flow Control Statements foreach ‘loop’ % vi marks 16 - | - | - | - | - | - | - | - | - |Fred Dexter 19 - | - | - | - | A | - | - | - | - |Waqas Younis 16 A | A | A | B | - | A | A | A | B |David Gower 16 - | - | - | - | A | - | - | - | - |Mickey Stewart 20 A | A | A | A | A | A | A | A | A |Graham Thorpe

LIN Flow Control Statements foreach ‘loop’ % vi countmarks #!/bin/csh # counts the number of students associated with a number of # particular marks foreach number( ) set ms=`grep "^$number " marks | wc -l` if ($ms != 0) then echo “$ms ' student(s) got ' $number marks” endif end Note: set ms= will set the variable ms to have the value that corresponds to the output of the grep and wc command line utilities.

LIN Flow Control Statements foreach ‘loop’ % chmod +x countmarks ; countmarks 3 student(s) got 16 marks 1 student(s) got 19 marks 1 student(s) got 20 marks Recall: The semicolon ; links two commands that are executed by the shell in simple sequential order; csh will run the first command in the sequence, then once that command is finished, it will run the next command.

LIN Flow Control Statements foreach ‘loop’ Example: % mkdir city; cd city; mkdir sf ny la; touch sf/a ny/b la/c Note: touch is a standard Unix program used to create a blank file; it is also used to change a file's access and modification timestamps.

LIN Flow Control Statements foreach ‘loop’ Example: % mkdir Try; cd Try; mkdir d1 d2 d3; touch d1/a d2/b d3/c % vi check #!/bin/csh set start=`pwd` set command=$0 foreach name (`ls`) if (-d $name) then (cd $name ; $start/$command) ; echo "end of directory $name" else echo "$name is a file" endif end

LIN Flow Control Statements foreach ‘loop’ Example: % chmod +x check ; check check is a file c is a file end of directory la b is a file end of directory ny a is a file end of directory sf

LIN Del Script #! /bin/csh # usage: del * foreach name ($argv) if ( -f $name ) then echo -n "delete the file '${name}' (y/n/q)?" else echo -n "delete the entire directory '${name}' (y/n/q)? " endif set ans = $< switch ($ans) case n: continue case q: exit case y: rm -r $name continue endsw end

LIN Del Script #! /bin/csh foreach name ($argv) # $argv shell variable for an argument of a command if ( -f $name ) then echo -n "delete the file '${name}' (y/n/q)?" else echo -n "delete the entire directory '${name}' (y/n/q)? " endif set ans = $< switch ($ans) case n: continue case q: exit case y: rm -r $name continue endsw end

LIN Del Script #! /bin/csh foreach name ($argv) if ( -f $name ) then # tests to see if the file whose name is in $name is an ordinary file, as opposed to a directory file. echo -n "delete the file '${name}' (y/n/q)?" else echo -n "delete the entire directory '${name}' (y/n/q)? " endif set ans = $< switch ($ans) case n: continue case q: exit case y: rm -r $name continue endsw end

LIN A note on File Operations Using the if command, filenames can be tested for the following: -d filename true if filename is a directory -e filename true if filename exists -f filename true if filename is a text file -o filename true if you own filename -r filename true if filename is readable -w filename true if filename is writable -x filename true if filename is executable -z filename true if filename is empty

LIN Del Script #! /bin/csh foreach name ($argv) if ( -f $name ) then echo -n "delete the file '${name}' (y/n/q)?” #The echo -n prevents a skip to a new line; the -n option of echo tells the shell not to print the newline # character, so that our answer, y/n/q, will be on the same line. else echo -n "delete the entire directory '${name}' (y/n/q)? " endif set ans = $< switch ($ans) case n: continue case q: exit case y: rm -r $name continue endsw end

LIN Del Script echo -n vs. echo The echo utility writes any specified operands, followed by a newline \n character The following option is available: -n Do not print the trailing newline character \n.

LIN Del Script #! /bin/csh foreach name ($argv) if ( -f $name ) then echo -n "delete the file '${name}' (y/n/q)?” else echo -n "delete the entire directory '${name}' (y/n/q)? " endif set ans = $< # the symbol $< means the input from the keyboard switch ($ans) case n: continue case q: exit case y: rm -r $name continue endsw end

LIN Del Script #! /bin/csh foreach name ($argv) if ( -f $name ) then echo -n "delete the file '${name}' (y/n/q)?" else echo -n "delete the entire directory '${name}' (y/n/q)?" endif set ans = $< switch ($ans) # Control flow is switched to where the first match occurs case n: continue # go to the top of the enclosing loop case q: exit case y: rm -r $name continue endsw end

LIN A note on SWITCH command The switch command takes the general form: switch ($variable)# Starts a switch case pattern1:# Defines a label in a switch command action breaksw case pattern2: action breaksw default : action endsw

LIN Del Script case y: rm -r $name # rm stands for "remove" and the -r option means recursively, if an argument of # rm -r is a directory, the rm -r command will remove that directory, and all the # files (and subdirectories, etc.) within it. # You can also use *, a wildcard for everything; rm will go through the current # working directory and remove all the files in it, and also through every subdirectory # and remove all the files in them. In short, # rm -r * deletes everything in the current directory and below.