Shell Script Examples.

Slides:



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

Find Command Characteristics –Locate files descending from multiple starting points –Employs regular expressions Examples On entire system: >find / -name.
CS 497C – Introduction to UNIX Lecture 22: - The Shell Chin-Chih Chang
CS Lecture 03 Outline Sed and awk from previous lecture Writing simple bash script Assignment 1 discussion 1CS 311 Operating SystemsLecture 03.
Now, return to the Unix Unix shells: Subshells--- Variable---1. Local 2. Environmental.
23-Jun-15Advanced Programming Spring 2002 bash Henning Schulzrinne Department of Computer Science Columbia University.
The UNIX Shells 1. What is a Unix shell? 2. A few common shells in the Unix & Linux. A. Bourne shell B. Korn shell C. C shell D. Bash-the default shell.
More Shell Basics CS465 - Unix. Unix shells User’s default shell - specified in /etc/passwd file To show which shell you are currently using: $ echo $SHELL.
The Bourne Shell 吳 瑞 麟 National Cheng Kung University, Computer and Network Center.
UNIX Filters.
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.
Second edition Your UNIX: The Ultimate Guide Das © 2006 The McGraw-Hill Companies, Inc. All rights reserved. UNIX – Shell Programming The activities of.
Using the Bash Shell. Linux Shell Options Linux provides a range of options for shells. bash –The GNU Bourne Again Shell (bash) bsh – The Bourne Shell.
Advanced File Processing
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.
Writing Shell Scripts ─ part 1 CSE 2031 Fall September 2015.
1 Operating Systems Lecture 3 Shell Scripts. 2 Brief review of unix1.txt n Glob Construct (metacharacters) and other special characters F ?, *, [] F Ex.
Agenda User Profile File (.profile) –Keyword Shell Variables Linux (Unix) filters –Purpose –Commands: grep, sort, awk cut, tr, wc, spell.
Chapter 5 Bourne Shells Scripts By C. Shing ITEC Dept Radford University.
1 Shell Programming – Extra Slides. 2 Counting the number of lines in a file #!/bin/sh #countLines1 filename=$1#Should check if arguments are given count=0.
An Introduction to Unix Shell Scripting
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 8 Shell.
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.
Chapter 4 UNIX Common Shells Commands By C. Shing ITEC Dept Radford University.
CS 6560 Operating System Design Lecture 3:Tour of GNU/Linux.
System Administration Introduction to Unix Session 2 – Fri 02 Nov 2007 Reference:  chapter 1, The Unix Programming Environment, Kernighan & Pike, ISBN.
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.
Introduction to Linux OS (IV) AUBG ICoSCIS Team Prof. Volin Karagiozov March, 09 – 10, 2013 SWU, Blagoevgrad.
OPERATING SYSTEMS DESIGN UNIX BASICS & SHELL SCRIPTING.
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 ?
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.
Chapter Five Advanced File Processing. 2 Objectives Use the pipe operator to redirect the output of one command to another command Use the grep command.
1 System Administration Introduction to Scripting, Perl Session 3 – Sat 10 Nov 2007 References:  chapter 1, The Unix Programming Environment, Kernighan.
Module 6 – Redirections, Pipes and Power Tools.. STDin 0 STDout 1 STDerr 2 Redirections.
Shell Programming. Creating Shell Scripts: Some Basic Principles A script name is arbitrary. Choose names that make it easy to quickly identify file function.
1 Operating Systems Lecture 2 UNIX and Shell Scripts.
Lecture 2: Advanced UNIX, shell scripts (ol)‏ Programming Tools And Environments.
Chapter Five Advanced File Processing. 2 Lesson A Selecting, Manipulating, and Formatting Information.
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.
CSCI 330 UNIX and Network Programming Unit IX: Shell Scripts.
CS252: Systems Programming Ninghui Li Slides by Prof. Gustavo Rodriguez-Rivera Topic 7: Unix Tools and Shell Scripts.
CSCI 330 UNIX and Network Programming Unit IV Shell, Part 2.
CSCI 330 UNIX and Network Programming Unit IV Shell, Part 2.
Agenda Positional Parameters / Continued... Command Substitution Bourne Shell / Bash Shell / Korn Shell Mathematical Expressions Bourne Shell / Bash Shell.
UNIX Shell Script (2) Dr. Tran, Van Hoai Faculty of Computer Science and Engineering HCMC Uni. of Technology
Chapter 5 The Bourne Shell Graham Glass and King Ables, UNIX for Programmers and Users, Third Edition, Pearson Prentice Hall, Notes by Michael Weeks.
CS 403: Programming Languages Lecture 20 Fall 2003 Department of Computer Science University of Alabama Joel Jones.
1 UNIX Operating Systems II Part 2: Shell Scripting Instructor: Stan Isaacs.
Shell Control Structures CSE 2031 Fall June 2016.
INTRODUCTION TO SHELL SCRIPTING By Byamukama Frank
Lesson 5-Exploring Utilities
Prepared by: Eng. Maryam Adel Abdel-Hady
The UNIX Shell Learning Objectives:
Shell Scripting March 1st, 2004 Class Meeting 7.
Lecture 9 Shell Programming – Command substitution
Tutorial of Unix Command & shell scriptS 5027
Tutorial of Unix Command & shell scriptS 5027
John Carelli, Instructor Kutztown University
UNIX Reference Sheets CSE 2031 Fall 2010.
Linux Shell Script Programming
Chapter 3 The UNIX Shells
Introduction to Bash Programming, part 3
Presentation transcript:

Shell Script Examples

A shell script is… A series of OS commands for execution Stored in a text file #!/bin/sh rm -f /tmp/listing.tmp > /dev/null 2>&1 touch /tmp/listing.tmp ls -l [a-z]*.doc | sort > /tmp/listing.tmp lpr -Ppostscript_1 /tmp/listing.tmp rm -f /tmp/listing.tmp

Components of a script Shell in use (sh, bash, csh) #!/bin/sh rm -f /tmp/listing.tmp > /dev/null 2>&1 touch /tmp/listing.tmp # This is a comment ls -l [a-z]*.doc | sort > /tmp/listing.tmp lpr -Ppostscript_1 /tmp/listing.tmp rm -f /tmp/listing.tmp Command Comment

How to invoke a script Correct way Simple way $ /bin/bash my_script arg_1 arg_2 Simple way $ my_script arg_1 arg_2 The first line specifying the shell must be provided in simple way

Definitions Blank = chunk of tab or space Name = sequence of ASCII letters, digits, underscores, beginning with a letter or underscore Argument = string supplied on command-line

Example (argument) (1) #!/bin/sh ############################## echo "Script name is [$0]" echo "First argument is [$1]" echo "Second argument is [$2]" echo "This process ID is [$$]" echo "This argument count is [$#]" echo "All arguments [$@]"

Example (argument) (2) :~> my_script.sh bhecker 1 university Script name is [my_script.sh] First argument is [bhecker] Second argument is [1] This process ID is [5401] This argument count is [3] All arguments [bhecker 1 university]

Filename meta characters * Match any string of zero or more characters ? Match any single character [abc...] Match any one of the enclosed characters; a hyphen can specify a range (e.g., a-z, A-Z, 0–9) [!abc...] Match any character not enclosed as above ~ Home directory of the current user ~name Home directory of user name ~+ Current working directory ($PWD) ~- Previous working directory ($OLDPWD)

Simple regular expressions (Korn shell) ?(pattern) Match zero or one instance of pattern *(pattern) Match zero or more instances of pattern +(pattern) Match one or more instances of pattern @(pattern) Match exactly one instance of pattern !(pattern) Match any strings that don't match pattern Pattern = sequence of patterns separated by “|”

Example (meta characters) List files having prefix new $ ls new* Cat files having prefix ch and one more letter $ cat ch? Vi files starting by letters from D to E $ vi [D-R]* Print files not *.o and core (Korn shell) $ pr !(*.o|core) | lp

Quoting "" Everything taken literally, except '' $ (variable substitution) ` (command substitution) “ (ending mark) '' Everything taken literally \ Character following \ taken literally

Example (quoting) $ echo 'my class is "unix and tools"' $ echo "Well, isn't that \"good\" ?" Well, isn't that "good" ? $ echo "You have `ls | wc –l` files in `pwd`" You have 34 files in /home/bhecker $ echo "The value of \$x is $x" The value of $x is 100

Variables (1) var=value… Set variable to value ${var} Use value of var Use var if set, otherwise, use value ${var:=value} Use var if set, otherwise, user value and assign it to var ${var:?value} Use var if set, otherwise, print value and exit ${var:+value} Use value of var is set, otherwise use nothing ${#var} Use the length of var ${#*} or ${#@} Use the number of positional arguments

Variables (2) ${var#pattern} Use value of var after removing pattern from the left. Remove shortest matching ${var##pattern} Same as #pattern. Remove longest matching ${var%pattern} Use value of var after removing pattern from the right. Remove shortest matching ${var%%pattern} Same as %pattern. Remove longest matching

Command forms cmd1 ; cmd2 Multiple commands on the same line Commands as a group in current shell (cmd1 ; cmd2) Commands as a group in a subshell cmd1 | cmd2 Pipe cmd1 `cmd2` Command substitution cmd1 $(cmd2) POSIX Command substitution (nesting is allowed) cmd $((expression)) POSIX shell arithmetic substitution cmd1 && cmd2 AND; cmd1, then cmd2 if (cmd succeeds) cmd1 || cmd2 OR ! cmd NOT; change exit status

Example (command forms) $ nroff file > file.txt & Format in the background $ cd; ls Execute sequentially $ (date; who; pwd) > logfile All output is redirected $ sort file | pr -3 | lp Sort file, page output, then print $ vi 'grep -l ifdef *.c' Edit files found by grep $ grep XX file && lp file Print file if it contains the pattern; $ grep XX file || echo "XX not found" otherwise, echo an error message

Simple commands sort Sort lines grep Search for regular expressions basename Get file name from path string dirname Get directory name from path string cut Chop up a text by strings or characters [(test)] Predicate or conditional processor tr 'a' 'b' Transform characters expr Simple arithmetic processor eval Evaluate variables date Create date strings head/tail Access lines in files

Example (script) (1) #!/bin/bash alphabet="a b c d e" # Initialize a string count=0 # Initialize a counter for letter in $alphabet # Set up a loop control do # Begin the loop count=‘expr $count + 1’ # Increment the counter # Display the result echo "Letter $count is [$letter]" done

Example (script) (2) alphabet="a b c d e" # Initialize a string count=0 # Initialize a counter while [ $count -lt 5 ] # Set up a loop control do # Begin the loop count=‘expr $count + 1’ # Increment the counter # Position of next letter position=‘bc $count + $count – 1’ letter=‘echo "$alphabet" | cut -c$position-$position’ # Get next letter # Display the result echo "Letter $count is [$letter]" done