TDC368 UNIX and Network Programming Camelia Zlatea, PhD Week 9:  Introduction to UNIX Shells  C-Shell.

Slides:



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

1 The Shell and some useful administrative Unix Commands How Unix works along with some additional, useful administrative Unix commands you might need.
NETW-240 Shells Last Update Copyright Kenneth M. Chipps Ph.D. 1.
CS 497C – Introduction to UNIX Lecture 26: - The Process 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.
Linux+ Guide to Linux Certification, Second Edition
Shell Basics CS465 - Unix. Shell Basics Shells provide: –Command interpretation –Multiple commands on a single line –Expansion of wildcard filenames –Redirection.
Now, return to the Unix Unix shells: Subshells--- Variable---1. Local 2. Environmental.
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).
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.
Unix Shell Scripts. What are scripts ? Text files in certain format that are run by another program Examples: –Perl –Javascript –Shell scripts (we learn.
CSCI 330 T HE UNIX S YSTEM C Shell Programming. S TEPS TO C REATE S HELL P ROGRAMS Specify shell to execute program Script must begin with #! (pronounced.
1 UNIX essentials (hands-on) the directory tree running programs the shell (using the T-shell) → command line processing → special characters → command.
Introduction to Linux and Shell Scripting Jacob Chan.
Shell Script Examples.
Lecture 3  Shell Variables  Shell Command History  Job / Process Control  Directory Control.
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.
Week 7 Working with the BASH Shell. Objectives  Redirect the input and output of a command  Identify and manipulate common shell environment variables.
Introduction to UNIX / Linux - 11
Chapter 6: Shell Programming
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.
Introduction to Unix – CS 21 Lecture 9. Lecture Overview Shell description Shell choices History Aliases Topic review.
Chapter 4 UNIX Common Shells Commands By C. Shing ITEC Dept Radford University.
Writing C-shell scripts #!/bin/csh # Author: Ken Berman # Date: # Purpose: display command and parameters echo $0 echo $argv[*]
July 17, 2003Serguei A. Mokhov, 1 Shells and Shell Scripts COMP 444/5201 Revision 1.3 January 25, 2005.
1 UNIX essentials (hands-on) the directory tree running programs the shell → command line processing → special characters → command types → shell variables.
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.
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 ?
Essential Shell Programming by Prof. Shylaja S S Head of the Dept. Dept. of Information Science & Engineering, P.E.S Institute of Technology, Bangalore
LINUX System : Lecture 6 Shell Programming
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
CS465 - UNIX The Bourne Shell.
UNIX Commands. Why UNIX Commands Are Noninteractive Command may take input from the output of another command (filters). May be scheduled to run at specific.
Shell Programming. 222 Lecture Overview  Shell variables  Shell scripts  Control flow and Boolean operators  Shell programming tips  Shell programming.
1 Week 2 The Crunchy Shell to the Soft and Chewy Kernel… Sarah Diesburg 8/3/2010 COP4610 / CGS5765.
Module 6 – Redirections, Pipes and Power Tools.. STDin 0 STDout 1 STDerr 2 Redirections.
1 © 2001 John Urrutia. All rights reserved. Chapter 10 using the Bourne Again Shell.
1 Operating Systems Lecture 2 UNIX and Shell Scripts.
Unix/Linux cs3353. The Shell The shell is a program that acts as the interface between the user and the kernel. –The shell is fully programmable and will.
1 Unix Seminar #1 T.J. Borrelli Lecturer for CS and NSSA February 6th, 2009.
Chapter 10: BASH Shell Scripting Fun with fi. In this chapter … Control structures File descriptors Variables.
Summer 2015 SILICON VALLEY UNIVERSITY CONFIDENTIAL 1 Introduction to UNIX / Linux - 13 Dr. Jerry Shiao, Silicon Valley University.
LIN Unix Lecture 5 Unix Shell Scripts. LIN Command Coordination ; && || command1 ; command2 Interpretation: Do command 1. Then do command.
Chapter Six Introduction to Shell Script Programming.
CSCI 330 UNIX and Network Programming Unit IX: Shell Scripts.
Lesson 3-Touring Utilities and System Features. Overview Employing fundamental utilities. Linux terminal sessions. Managing input and output. Using special.
1 Unix/Linux commands and shell programming-Part 2 (Dr. Mohamed El Bachir Menai)
CSCI 330 UNIX and Network Programming Unit III Shell, Part 1.
Linux+ Guide to Linux Certification, Second Edition
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.
1 © 2012 John Urrutia. All rights reserved. Chapter 09 The TC Shell.
1 Lecture 7 Introduction to Shell Scripts COP 3353 Introduction to UNIX.
1 UNIX Operating Systems II Part 2: Shell Scripting Instructor: Stan Isaacs.
Linux Administration Working with the BASH Shell.
Introduction to Shells
The UNIX Shell Learning Objectives:
LINUX System : Lecture 5 (English-Only Lecture)
Shell Programming (ch 10)
Shell Programming.
Linux Shell Script Programming
Chapter 3 The UNIX Shells
Introduction to Bash Programming, part 3
Essential Shell Programming
Presentation transcript:

TDC368 UNIX and Network Programming Camelia Zlatea, PhD Week 9:  Introduction to UNIX Shells  C-Shell Interactive Commands  C Shell Programming

UNIX Network Programming – TDC Page 2 Spring 2003 References  Ellie Quingley, UNIX Shells by Example, Prentice Hall PTR, NJ, 1997 chap.9 (pp )  Dave Curry, UNIX Systems Programming for SVR4, O'Reilly & Assoc., Sebastopol, CA,  UNIX in a Nutshell, by Daniel Gilly, O’Reilly & Associates, Inc., section 5.

UNIX Network Programming – TDC Page 3 Spring 2003 Introduction to UNIX Shells  shell – the program interface between the user and the kernel functions: –reading user input and parse the command line –managing processes and jobs; redirection, pipes –handling signals –executing scripts  System Startup –process init (pid=1), the first process to run after the system boots will fork and exec a program that handle terminals (getty). –getty activates the terminal port; stdin, stdout and stderr. –same process executes next the command "/bin/login"; prompts for user name and password; validate the input by reading the correspondent entry from /etc/passwd; setup working environment –executes user predefined shell (ex. "/bin/csh")  Environment Initialization (C Shell) –C shell executes the file.cshrc (this is executed anytime when a new C shell is started) –C shell executes.login file –C shell prompt is displayed as a fact that shell is waiting to process user command

UNIX Network Programming – TDC Page 4 Spring 2003 Introduction to UNIX Shells  ? How to change your login shell: passwd –e (on HP)  File.cshrc contains C shell variables settings  Example: set history=20 # previous commands to remember. set savehist=20 # number to save across sessions. set system=`hostname` # name of this system. set prompt = "$system\:> " # command prompt. set autologout=20 alias l ls alias info ‘(who am i; date )’

UNIX Network Programming – TDC Page 5 Spring 2003 Introduction to UNIX Shells  File.login contains environment variables and terminal settings; this information is inherited by shell’s children processes.  Example: setenv TERM ansi umask 077 echo Hello $LOGNAME echo The date is 'date' echo Your home shell is $SHELL echo Good-bye $LOGNAME  ? How to re-execute a modified.chsrc or.login, in the current shell source.login or source.cshrc

UNIX Network Programming – TDC Page 6 Spring 2003 C-Shell Interactive Commands  Command Line –C shell status variable returns is set to the exit status (0 to 255) of the last executed command(0 – success)  Sequential execution of commands (;) –Example: who am i; pwd ; date  Conditional Execution (&& ||) –Example: grep ‘czlatea’ /etc/passwd && talk czlatea –# if command grep is successful (status 0) then mail command is executed –Example: grep ‘tdc368’ /etc/passwd || echo "user tdc368 unknown"  Pipelined Execution (|) –ls –l | sort  Background Execution (&) –man csh | cat >csh.doc &  Command line history: history –!! # re-executing last command –!6 # the sixth command from history is executed

UNIX Network Programming – TDC Page 7 Spring 2003 C-Shell Interactive Commands  Command Line Arguments !:1 – first, !:2 second, !:3 third ….. !$ - last, !^ - first, !* - all arguments –Example: echo a b c d !:0 !$ # re-execute the last command (echo) with only its last argument  Job Control jobs Bg fg suspend jobs (^Z)  Metacharacters ls a* # list all files starting wirh a ls [aA]*#list all files starting with a or A ls *[0-9] #list all file ending with a digit ls *[.][0-9] #list allfiles ending with a period followed by a digit ls ?? #list all files with two-character name ls [A-Z][A-Z][A-Z] #list all files with three uppercase character name ls *{11,22} #list all files ending in 11 or 22

UNIX Network Programming – TDC Page 8 Spring 2003 C-Shell Interactive Commands  Redirectation, Pipes –( >, &, >>, >>&, << HERE, |, |&  Example: Here Document cat << HERE This is a test for input re-directation. This show a here document. HERE –the output of command cat is the "here document" from first HERE to second HERE

UNIX Network Programming – TDC Page 9 Spring 2003 C-Shell Interactive Commands  Redirectation of both output and error standard files >& –ls -l | grep May > & outfile –separate redirectation of stderr and stdin –( ls -l | grep May > result1 ) > & error  C shell process forks a child to execute the above command –The child process redirects its stderr and stdout to file errors –The child process forks a new process –The new process executes the command file in (.. ); it inherits the file descriptors of its father; it redirects again its stdout to file results.

UNIX Network Programming – TDC Page 10 Spring 2003 Variables in C Shell  Local variables: visible in the shell were was defined  Environment variables: visible in the shell and all processes spawned by this shell  Example: set history = 50 # set the build-in variables set savehist = 10 # history and savehist set person = Doe # set user variable username set machine = `uname –n` # and machine echo $?machine # test to see if variable machine is defined (set) echo $machine # echo the value of variable machine, if it is defined set var = noon # user variable echo after${var} set var = "Hello World" echo $var setenv PERSON="Joe Doe" # set an environment variable echo $PERSON set # displays all local variables set for the current shell env #display all environment variables setenv

UNIX Network Programming – TDC Page 11 Spring 2003 Arrays and Strings  Examples: set persons = (Joe Liz Tom Dan) # an array variable echo $persons # display the variable echo $persons[*] #same echo $#persons# display the number of elements echo $persons[$#persons] # display the last element echo $persons[1] #display first element of the array set $persons[1] = John #reassign first element echo $persons[3-4] # list elements 3 and 4 of the array echo $persons[10] # out of range shift persons # shift one position to the left the array values set days = "Monday Tuesday Wednesday" #a string variable, not an array set days = ($days) #converts the string into an array set var1 = `date`# the output of the command date is stored as an array set var2 = “`date`" # the output is stored as a single string

UNIX Network Programming – TDC Page 12 Spring 2003 Special variables  $$ - displays the PID of current shell  $< - accepts input from the user  Backslash Character: - escape the interpretation of a single character (ex. ?, !, newline)

UNIX Network Programming – TDC Page 13 Spring 2003 C-Shell Programming  Shell Scripts –The magic number - #!/bin/csh first line of the script  Examples: #!/bin/csh echo Hello $LOGNAME echo The date is `date` echo Your home shell is $SHELL echo "This machine is `uname –n`" echo The calendar for this month is cal echo The processes you are running are: ps -al | grep "^ *$LOGNAME" echo "Thanks for coming. See you soon\!\!" echo Good-bye $LOGNAME

UNIX Network Programming – TDC Page 14 Spring 2003 Debugging scripts: set/unset echo  set/unset verbose #!/bin/csh echo Hello $LOGNAME echo The date is `date` set verbose echo Your home shell is $SHELL unset verbose echo Good-bye $LOGNAME

UNIX Network Programming – TDC Page 15 Spring 2003 Variables  set varname = # assignment $< variable # reading user input  Numeric Variables - Arithmetic Expressions Operators: + - / * > (right shift) +=, -+, *=, /=, ++, --  var = 5+ 3 echo sum += 1 # same sum sum +1 echo $sum

UNIX Network Programming – TDC Page 16 Spring 2003 Command Line Arguments  $0, $1,.., $9, ${10}, ${11},.. $* - all arguments $argv[1], $argv[2], …. – first, second arg... $#argv number of arguments $argv[*] all arguments  Example: #!/bin/csh -f # The greetings script # This script greets a user whose name is typed in at the command line. echo $0 to you $1 $2 $3 set d = ‘date’ set dd = $d[1-3] echo Welcome to this day $dd echo Hope you have a nice day, $argv[1] \! echo Good-bye $argv[1] $argv[2] $argv[3] greetings Joe Doe

UNIX Network Programming – TDC Page 17 Spring 2003 Decisions  if, if-else, switch  Examples: Conditions and File testing #!/bin/csh -f # Script name: logical set x = 1 set y = 2 set z = 3 if (( "$x" && "$y" ) || ! "$z" ) then # grouping echo TRUE else echo FALSE endif

UNIX Network Programming – TDC Page 18 Spring 2003 Example #!/bin/csh -f # Scriptname: filecheck # Usage: filecheck filename set file=$1 if ( ! -e $file ) then echo "$file does not exist" exit 1 endif if ( -d $file ) then echo "$file is a directory" else if ( -f $file ) then if ( -r $file && -x $file ) then # nested if construct echo "You have read and execute permission on file $file. endif else print "$file is neither a plain file nor a directory. " endif

UNIX Network Programming – TDC Page 19 Spring 2003 Example: system type Testing #!/bin/csh -f # Program to determine the type of system you are on. echo "Your system type is: " set release = `uname -n`; echo $release switch ( `uname -s`) case SunOS: echo SunOs breaksw case HP-UX: echo HP breaksw case Linux: echo Linux breaksw endsw

UNIX Network Programming – TDC Page 20 Spring 2003 Loops  foreach variable (list) commands end  Example #!/bin/csh -f foreach file (*.o) rm $file end  while (condition) Command end  Example #!/bin/csh -f # Script is called loop.args while ( $#argv ) echo $argv shift end condor:> csh t2 a b c d e a b c d e b c d e c d e d e e condor:>

UNIX Network Programming – TDC Page 21 Spring 2003 Loop  repeat n commands #!/bin/csh -f while ( $#argv ) echo $argv shift end #!/bin/csh -f while (1) echo "Hello, in 1st loop" while (1) echo "In 2nd loop" while (1) echo "In 3rd loop" repeat 3 break end echo "Out of all loops"

UNIX Network Programming – TDC Page 22 Spring 2003 Signals Handling  An INT signal (ctrl-C) can be caught only from with a script #!/bin/csh onintr done # install signal handler – label done sleep 30 # other scripts commands echo Bye noINT exit done: # signal handler echo hello int onintr - # disable interupts ls -l echo Bye

UNIX Network Programming – TDC Page 23 Spring 2003 Setting Executable Scripts  setuid scripts  chmod u+sx script_file

UNIX Network Programming – TDC Page 24 Spring 2003 A C shell script to add new data entries to a phone list file 1/3 #!/bin/csh -f set phonefile = phone.list startover: while (1) echo "First Name (stop to exit): " set fname = $< # read input variable if ($fname =~ [Ss][Tt][Oo][Pp]*) then break # exit if stop is typed endif echo "Last Name (XX to restart) " set lname = $< if ($lname =~ "XX")then goto startover # skip rest of the loop endif echo "$fname $lname's phone number (XX to restart): " set phnbr = $< if ($phnbr =~ "XX")then goto startover # skip rest of the loop endif

UNIX Network Programming – TDC Page 25 Spring 2003 A C shell script to add new data entries to a phone list file2/3 # search for a duplicate entry if {(egrep "$lname, $fname $phnbr" $phonefile)} then echo "Duplicates were found in the list " endif while (1) echo "Cancel this entry? (y/n) " set answer = $< if ($answer =~ [Yy]*) then goto startover else break endif end endif

UNIX Network Programming – TDC Page 26 Spring 2003 A C shell script to add new data entries to a phone list file3/3 # insert entry set correct=n while ("$correct" !~ [Yy]*) echo "1 $fname“ ; echo "2 $lname“ ; echo "3 $phnbr“ ; echo "Is this correct ? (y/n)" set answer=$< if ("$answer" =~ [Yy]*) then set correct=y else echo "Number to correct: " set num = $< switch ($num) case 1: echo "Last Name: " set fname = $< breaksw case 2: echo "Last Name: " set lname = $< breaksw case 3: echo "Phone Number: " set phnbr = $< breaksw endsw endif end # end while... correct echo "$lname, $fname $phnbr" >> $phonefile end # first while echo "Done"

UNIX Network Programming – TDC Page 27 Spring 2003 A C shell script to find a pattern in a phone list file #!/bin/csh -f set phonefile = phone.list switch ($#argv) case 0: echo "Usage: $0 pattern” echo "pattern is what to look for in the phone list" breaksw default:foreach pattern ($*) echo $pattern grep "$pattern" $phonefile || echo "$pattern not found in $phonefile“ end breaksw endsw echo "Done"

UNIX Network Programming – TDC Page 28 Spring 2003 A C shell script to find a multiple pattern in a phone list file #!/bin/csh -f set phonefile = phone.list switch ($#argv ) case 0: echo "Usage: $0 pattern echo "pattern is what to look for in the phone list" breaksw default:set counter=0 foreach pattern ($*) if {(grep "$pattern" $phonefile)} counter++ else echo "$pattern not found in $phonefile" endif end breaksw endsw echo "Matched $counter patterns" echo "Done"

UNIX Network Programming – TDC Page 29 Spring 2003 Example #!/bin/csh -f # A C shell script to take two arguments and substitute the second argument # for the first, writing the resulting corrections back into the phone list file set phonefile = phone.list switch ($#argv) case 2: sed "s/$1/$2/g" $phonefile > /tmp/chg.tmp mv /tmp/chg.tmp $phonefile breaksw default: echo "Usage: $0 old new echo "$0 substitutes old for new in the $phonelist" breaksw endsw echo "Done"