240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell...

85
40-491 Adv. UNIX:CShell/7 Advanced UNIX Advanced UNIX Objectives of these slides: Objectives of these slides: introduce the C Shell introduce the C Shell concentrate on features not in the concentrate on features not in the Bourne Shell (but many are in Bash) Bourne Shell (but many are in Bash) 240-491 Special Topics in Comp. Eng. 1 Semester 2, 2000-2001 7. The C Shell (Chapter 11, Sobell)

Transcript of 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell...

Page 1: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 1

Advanced UNIXAdvanced UNIX

Objectives of these slides:Objectives of these slides:– introduce the C Shellintroduce the C Shell

– concentrate on features not in the Bourne Shell concentrate on features not in the Bourne Shell (but many are in Bash)(but many are in Bash)

240-491 Special Topics in Comp. Eng. 1Semester 2, 2000-2001

7. The C Shell(Chapter 11, Sobell)

Page 2: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 2

OverviewOverview

1. 1. BackgroundBackground

2. 2. HistoryHistory

3. 3. AliasAlias

4. 4. Job ControlJob Control

5. 5. Home Directory Short FormsHome Directory Short Forms

continued

Page 3: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 3

6. 6. Filename CompletionFilename Completion

7. 7. Directory StacksDirectory Stacks

8. 8. VariablesVariables

9. 9. Automated ScriptsAutomated Scripts

10.10. Script ProgrammingScript Programming

Page 4: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 4

1. Background1. Background

Originally part of Berkeley UNIXOriginally part of Berkeley UNIX More tolerant of mistakes than BourneMore tolerant of mistakes than Bourne

– e.g can avoid accidental logouts, overwritese.g can avoid accidental logouts, overwrites Easier to configureEasier to configure

– e.g. alias, history, job controle.g. alias, history, job control Some scripting improvements over Bourne:Some scripting improvements over Bourne:

– better variables, arrays, expressionsbetter variables, arrays, expressions

continued

Page 5: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 5

Almost all the good ideas from the C Shell Almost all the good ideas from the C Shell have been added to Bash:have been added to Bash:– e.g. history, aliases, job control, directory e.g. history, aliases, job control, directory

stacksstacks

I use Bash for scripting I use Bash for scripting andand as my as my command interpreter. command interpreter.

Page 6: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 6

Entering & leaving the C ShellEntering & leaving the C Shell

Check your default shell with Check your default shell with psps

Change shell using Change shell using chshchsh or type or type cshcsh

Exit with: Exit with: exitexit, , logoutlogout

((control-Dcontrol-D maybe) maybe)csh is actually tcsh on most Linuxes

Page 7: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 7

2. History2. History

A list of recently used command lines A list of recently used command lines (events) that can be reused.(events) that can be reused.

$ set history = 25$ set history = 25 (record 25 events)(record 25 events)$ set savehist = 20$ set savehist = 20 (remember 20 events (remember 20 events

after logout) after logout)$ history$ history (see history list)(see history list)

Page 8: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 8

Using the history listUsing the history list

$ !!$ !! (execute last event)(execute last event)

$ !<number>$ !<number> (execute event no. (execute event no. <number><number>))$ !3$ !3

$ !<initial-text>$ !<initial-text> (execute most recent (execute most recent command that starts with command that starts with initial-textinitial-text))

$ !gcc$ !gcc

$ !loc$ !loc

Page 9: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 9

Bash HistoryBash History history [ number ]history [ number ]

– lists the last lists the last numbernumber commands! commands!

Bash supports the same history list features:Bash supports the same history list features:– !!!!, , !<number>!<number>, , !<text>!<text>

Relevant environment variables:Relevant environment variables:– HISTFILE=/home/ad/.bash_historyHISTFILE=/home/ad/.bash_history– HISTFILESIZE=500HISTFILESIZE=500– HISTSIZE=500HISTSIZE=500

continued

Page 10: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 10

In Bash, you can modify the prompt to In Bash, you can modify the prompt to include the history number.include the history number.

Inside Inside .bashrc.bashrc::PS1="\!.\u@\h$ "PS1="\!.\u@\h$ "

\! includes thehistory number

Page 11: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 11

3. Alias3. Alias

Define new commands by using string Define new commands by using string substitution.substitution.

Format:Format:$ alias new-command executed-command(s)$ alias new-command executed-command(s)

e.g.e.g.$ alias ll ls -lg$ alias ll ls -lg$ ll$ ll

Page 12: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 12

ExamplesExamples

$ alias ls ls -lg$ alias ls ls -lg

$ alias mi mv -i$ alias mi mv -i

$ alias who ’who ; date’$ alias who ’who ; date’

redefining commandsis okay

Page 13: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 13

Argument SubstitutionArgument Substitution

\!^\!^ the the first argumentfirst argument of the new command of the new command \!*\!* all the argumentsall the arguments of the new command of the new command

$ alias wid ’who | fgrep \!^’$ alias wid ’who | fgrep \!^’

$ wid igor$ wid igor

is the same as:is the same as:$ who | fgrep igor$ who | fgrep igor

Page 14: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 14

Check your aliasesCheck your aliases

$ alias$ alias (list the current aliases)(list the current aliases)

$ alias hd$ alias hd (check (check hdhd alias) alias)

$ unalias hd$ unalias hd (cancel (cancel hdhd alias) alias)

$ \ls$ \ls (use original meaning of (use original meaning of lsls))

sysAdmin safety style

Page 15: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 15

Bash AliasBash Alias

Bash alias works the same way at the Bash alias works the same way at the command line as in command line as in cshcsh::

aliasalias, , unaliasunalias, , \command\command

Defining an alias in Defining an alias in .bashrc.bashrc is is differentdifferent::alias namealias name==valuevalue

alias ls='/bin/ls -F'alias ls='/bin/ls -F' alias ll='ls -l'alias ll='ls -l' alias h="history 30"alias h="history 30"

continued

Page 16: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 16

Aliases that require multiple commands or Aliases that require multiple commands or arguments are defined as functions:arguments are defined as functions:

sgrep()sgrep(){{ ps aux | grep ps aux | grep $1$1 | grep -v grep | grep -v grep}}

cs()cs(){{ cd cd $1$1 ls ls}}

Page 17: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 17

4. Job Control4. Job Control

Move commands between foreground Move commands between foreground and background; suspend commands.and background; suspend commands.

Each background job has a PID and a Each background job has a PID and a job number.job number.

Page 18: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 18

ExampleExample

$ spell glossary > glossary.out &$ spell glossary > glossary.out &[1] 26025[1] 26025

$ date &$ date &[2] 26028[2] 26028Fri Jun 6 16:56:11 GMT+7 2000Fri Jun 6 16:56:11 GMT+7 2000[2] Done [2] Done datedate

$ gcc big.c &$ gcc big.c &[2] 26041[2] 26041

finishedalready

continued

Page 19: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 19

$ jobs$ jobs[1] - Running[1] - Running spell glossary.out > glospell glossary.out > glo[2] + Running[2] + Running gcc big.cgcc big.c

Other status messages:Other status messages:– StoppedStopped– Stopped (tty input)Stopped (tty input)– DoneDone

one before last

the last one

Page 20: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 20

BackgroundBackground to Foreground to Foreground

$ fg %job-number$ fg %job-number

Example:Example:$ fg %2$ fg %2

Page 21: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 21

Foreground to Foreground to BackgroundBackground

$ control-Z$ control-Z (suspends job and puts it (suspends job and puts it into the background)into the background)

$ bg$ bg (resumes the job)(resumes the job)

$ bg %job-number$ bg %job-number (resumes (resumes job-numberjob-number))

Page 22: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 22

StoppingStopping

$ stop %job-number$ stop %job-number

$ kill %job-number$ kill %job-number (kills (kills job-job-

numbernumber))

A job stopped for tty input must be brought A job stopped for tty input must be brought to the foreground (with to the foreground (with fgfg).).

Page 23: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 23

State Change State Change

The C Shell prints a message at the next The C Shell prints a message at the next prompt when the state of a job changes.prompt when the state of a job changes.

Use Use notifynotify to make the shell report a to make the shell report a change immediately:change immediately:

$ notify %job-number$ notify %job-number

Page 24: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 24

5. Home Directory Short Forms5. Home Directory Short Forms

~~ (your home directory)(your home directory)

~name~name (home directory of (home directory of name)name)

e.g. e.g. ~ad~ad

Use:Use:$ cp idea.txt ~$ cp idea.txt ~

$ ls ~ad/teach$ ls ~ad/teach

Page 25: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 25

6. Filename Completion6. Filename Completion

$ set filec$ set filec (‘switch on’ file completion)(‘switch on’ file completion)

$ cat trig1A $ cat trig1A <press <press escesc>>$ cat trig1A.txt$ cat trig1A.txt

Page 26: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 26

Control-D for helpControl-D for help

$ ls h*$ ls h*help.hist help.text help.trig.01help.hist help.text help.trig.01

$ cat h $ cat h <press <press escesc>>$cat help. $cat help. <beep><beep> <press <press control-Dcontrol-D>>help.hist help.text help.trig.01help.hist help.text help.trig.01$ cat help.$ cat help.

sometimes <tab>

Page 27: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 27

~

7. Directory Stacks7. Directory Stacks

Store a list of directories you are using Store a list of directories you are using on a on a stackstack..

Switch between directories by Switch between directories by referring to the stack.referring to the stack.

adv-unixcops_104

Page 28: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 28

~

$ pwd/home/ad/

$ pushd ~/teach/adv-unix~/teach/adv-unix ~

$ pwd/home/ad/teach/adv-unix

$ pushd ~/cops_104~/cops_104 ~/teach/adv-unix ~

$ pwd/home/ad/cops_104

adv-unixcops_104

push the directoryonto the stackand do a cd

Page 29: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 29

~

Change directories quicklyChange directories quickly

$ pushd~/teach/adv-unix ~/cops_104 ~

$ pwd/home/ad/teach/adv-unix/

cops_104adv-unix

push the top directorydown and do a cd

Page 30: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 30

$ pushd~/cops_104 ~/teach/adv-unix ~

$ pwd/home/ad/cops_104

~adv-unixcops_104

push the top directorydown and do a cd

Page 31: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 31

~

PopdPopd

$ popd~/teach/adv-unix ~

$ pwd

/home/ad/teach/adv-unix/

adv-unix

pop the top directoryand cd to the new top

Page 32: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 32

Other Stack CommandsOther Stack Commands

$ dirs$ dirs (lists the directories on (lists the directories on the stack)the stack)

$ pushd +number$ pushd +number

– move the directory in position move the directory in position numbernumber to the to the top (0), and cd to that directorytop (0), and cd to that directory

– the stack is numbered 0, 1, 2, ...the stack is numbered 0, 1, 2, ...

continued

Page 33: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 33

$ popd +number$ popd +number

– pop off the directory at position pop off the directory at position numbernumber

– if if numbernumber is not 0 then there is no change to is not 0 then there is no change to the present directorythe present directory

Page 34: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 34

8. Variables8. Variables

8.1. 8.1. String VariablesString Variables

8.2. 8.2. Numerical VariablesNumerical Variables

8.3. 8.3. Special Forms of User VariablesSpecial Forms of User Variables

8.4. 8.4. Shell VariablesShell Variables

Page 35: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 35

8.1. String Variables8.1. String Variables

$ set name = fred$ set name = fred (include spaces in(include spaces in older older cshcsh's)'s)

$ echo $name$ echo $namefredfred

$ set$ set (list set variables)(list set variables)

$ unset name$ unset name (delete name var)(delete name var)

Page 36: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 36

setenv (environment vars)setenv (environment vars)

$ setenv name fred$ setenv name fred$ echo $name$ echo $namefredfred$ setenv$ setenv$ unsetenv name$ unsetenv name

setenvsetenv makes the variable visible to any makes the variable visible to any scripts called from the shell (or from the scripts called from the shell (or from the script containing the script containing the setenvsetenv).).

no =

Page 37: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 37

Arrays of String VarsArrays of String Vars

$ set colours = (red green blue orange)$ set colours = (red green blue orange)

$ echo $colours$ echo $coloursred green blue orangered green blue orange

$ echo $colours[3]$ echo $colours[3]blueblue

$ echo $colours[2-4]$ echo $colours[2-4]green blue orangegreen blue orange

continued

Page 38: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 38

$ set shapes = (’’ ’’ ’’ ’’ ’’)$ set shapes = (’’ ’’ ’’ ’’ ’’)

$ echo $shapes$ echo $shapes

$ set shapes[4] = square$ set shapes[4] = square

$ echo $shapes[4]$ echo $shapes[4]squaresquare

Page 39: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 39

BracesBraces

Use Use {...}{...} to distinguish a variable from to distinguish a variable from surrounding text.surrounding text.

$ set prefix = Alex$ set prefix = Alex

$ echo $prefix is short for$ echo $prefix is short for {$prefix}ander.{$prefix}ander.Alex is short for Alexander.Alex is short for Alexander.

Can also write Can also write $prefix{ander}$prefix{ander}

Page 40: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 40

8.2. Numeric Variables8.2. Numeric Variables Use the Use the @@ command for variables holding numbers. command for variables holding numbers.

$ @ count = 0$ @ count = 0 (or (or set count = 0set count = 0))$ echo $count$ echo $count00$ @ count = ( 5 + 2 )$ @ count = ( 5 + 2 )$ echo $count$ echo $count77$ @ result = ( $count < 5 )$ @ result = ( $count < 5 )$ echo $result$ echo $result00

continued

Rememberthe space after the @

Page 41: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 41

$ @ count = $count + 5$ @ count = $count + 5$ echo $count$ echo $count1212

Could write:Could write:$ @ count += 5$ @ count += 5

$ @ count++$ @ count++$ echo $count$ echo $count1313

Page 42: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 42

OperatorsOperators

Most of the C numerical operators:Most of the C numerical operators:

– Arithmetic:Arithmetic: + - * / %+ - * / %– Relational:Relational: > < >= <= != ==> < >= <= != ==– Logical:Logical: && || !&& || !– etc.etc.

Page 43: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 43

Arrays of Numeric VarsArrays of Numeric Vars

$ set ages = (0 0 0 0 0)$ set ages = (0 0 0 0 0)

$ @ ages[2] = 15$ @ ages[2] = 15

$ @ ages[3] = ( $ages[2] + 4 )$ @ ages[3] = ( $ages[2] + 4 )

$ echo $ages[3]$ echo $ages[3]1919

$ echo $ages$ echo $ages0 15 19 0 00 15 19 0 0

Page 44: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 44

Bourne Shell EquivalentsBourne Shell Equivalents

The Bourne Shell only has string variables.The Bourne Shell only has string variables. It uses It uses exprexpr to switch string variables into to switch string variables into

numbers:numbers:

$ number=5$ number=5 (Bourne)(Bourne)$ number=‘expr $number + 2‘$ number=‘expr $number + 2‘

$ @ number = 5$ @ number = 5 (C Shell)(C Shell)$ @ number = $number + 2$ @ number = $number + 2

Page 45: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 45

8.3. Special Forms of User Variables8.3. Special Forms of User Variables

$#VAR$#VAR (returns number of elements (returns number of elements in in VARVAR array) array)

$?VAR$?VAR (returns 1 if (returns 1 if VARVAR is declared; is declared; 0 otherwise) 0 otherwise)

Page 46: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 46

$ set days = (mon tues wed thurs fri)$ set days = (mon tues wed thurs fri)

$ echo $#days$ echo $#days55

$ echo $?days$ echo $?days11

$ unset days$ unset days

$ echo $?days$ echo $?days00

days is declared

days is not declared

Page 47: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 47

8.4. Shell Variables8.4. Shell Variables

Shell variables can be initialised in three Shell variables can be initialised in three ways:ways:– by the shellby the shell– by the environmentby the environment

– by the user with by the user with setset or or setenvsetenv

continued

Page 48: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 48

There are two types of shell variable:There are two types of shell variable:– shell variables that take values;shell variables that take values;

– shell variables that act as switchesshell variables that act as switches they have the value 0 or 1they have the value 0 or 1

Page 49: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 49

Shell Vars that take ValuesShell Vars that take Values

$argv[0]$argv[0] or or $0$0 command namecommand name $argv[1]$argv[1] or or $$11 first argument first argument

of commandof command Also Also $$22,,$3$3,... ,...

– no upper limit; no need for no upper limit; no need for shiftshift

$argv[*]$argv[*] or or $*$* array of all argumentsarray of all arguments $#argv$#argv number of argumentsnumber of arguments

continued

Page 50: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 50

$HOME$HOME pathname to user’s pathname to user’s home directoryhome directory

$PATH$PATH array of pathnamesarray of pathnamesto commandsto commands

$ setenv PATH (/usr/bin /usr/ucb /bin ~/bin)$ setenv PATH (/usr/bin /usr/ucb /bin ~/bin)

$status$status exit status of last commandexit status of last command

etc...etc...

Page 51: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 51

Shell Vars that act as SwichesShell Vars that act as Swiches $filec$filec turns on file completionturns on file completion

$ignoreeof$ignoreeof disables disables ctrl-Dctrl-D as logout as logout

$noclobber$noclobber stops file overwriting with >stops file overwriting with >

$notify$notify immediate notification immediate notification about about

background job changesbackground job changes etc... etc...

Use: $ set ignoreeof

Page 52: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 52

9. Automated Scripts9. Automated Scripts At login, the C Shell executes a range of scripts At login, the C Shell executes a range of scripts

automatically:automatically:– /etc/csh.login/etc/csh.login, , /etc/csh.cshrc/etc/csh.cshrc

– .login.login in your home directory in your home directory– .cshrc.cshrc in your home directory in your home directory

At logout, it executes:At logout, it executes:– /etc/csh.logout/etc/csh.logout

– .logout.logout in your home directory in your home directory

continued

Page 53: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 53

When a shell script is called, the shell will When a shell script is called, the shell will execute the execute the cshrccshrc scripts first. scripts first.

The The cshrccshrc scripts are also executed scripts are also executed whenever a new window is created in a X-whenever a new window is created in a X-Windows session.Windows session.

Page 54: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 54

ExamplesExamples

$ cat .login$ cat .loginsetenv TERM vt100setenv TERM vt100stty erase ‘^X’ kill ‘^U’ -lcase -tabsstty erase ‘^X’ kill ‘^U’ -lcase -tabsecho “This is who is on the machine:”echo “This is who is on the machine:”whowho

Page 55: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 55

$ cat .cshrc$ cat .cshrcset noclobberset noclobberset ignoreofset ignoreofset history = 100set history = 100set prompt = “! % “set prompt = “! % “set PATH = (/usr/bin /usr/ucb /bin ~/bin)set PATH = (/usr/bin /usr/ucb /bin ~/bin)

alias h historyalias h historyalias ll ls -lgalias ll ls -lg

Only set is needed(not setenv), since.cshrc is executed atthe start of every script.

Page 56: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 56

$ cat .logout$ cat .logoutecho Switch off the air-conditionerecho Switch off the air-conditionersleep 10sleep 10

Page 57: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 57

10. Script Programming10. Script Programming

10.1. Executing a C Shell Script10.1. Executing a C Shell Script

10.2. Branching10.2. Branching

10.3. Looping10.3. Looping

10.4. Recursion10.4. Recursion

10.5. Interrupt Handling10.5. Interrupt Handling

Page 58: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 58

10.1. Executing a C Shell Script10.1. Executing a C Shell Script

Put Put #!/bin/csh#!/bin/csh as the first line as the first line– may need may need #!/bin/csh -f#!/bin/csh -f to switch off the default initial to switch off the default initial

execution of the execution of the cshrccshrc scripts scripts

Or execute:Or execute:$ csh script$ csh script

Or make Or make cshcsh your default shell. your default shell.

Page 59: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 59

10.2. Branching10.2. Branching

10.2.1.10.2.1. if-then if-then 10.2.2.10.2.2. File Test Expressions File Test Expressions 10.2.3. Switch10.2.3. Switch

Page 60: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 60

10.2.1. if-then10.2.1. if-then

Formats:Formats:

if (expression) thenif (expression) then commands commandsendifendif

if (expression) thenif (expression) then commands commandselseelse commands commandsendifendif

continued

Page 61: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 61

if (expression) thenif (expression) then commands commandselse if (expression) thenelse if (expression) then commands commands : :elseelse commands commandsendifendif

Page 62: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 62

$ cat if_else1$ cat if_else1#!/bin/csh -f#!/bin/csh -f# Set class depending on argument value# Set class depending on argument value

set number = $argv[1]set number = $argv[1]if ($number < 0) thenif ($number < 0) then @ class = 0 @ class = 0else if ($number >= 0 && $number < 100) thenelse if ($number >= 0 && $number < 100) then @ class = 1 @ class = 1else if ($number >= 100 && $number < 200)thenelse if ($number >= 100 && $number < 200)then @ class = 2 @ class = 2elseelse @ class = 3 @ class = 3endifendifecho The number $number is in class $classecho The number $number is in class $class

Page 63: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 63

UsageUsage

Due to the Due to the #!/bin/csh#!/bin/csh line, the script can be line, the script can be executed from the Bourne/Bash command executed from the Bourne/Bash command line:line:

$ if_else1 55$ if_else1 55The number 55 is in class 1The number 55 is in class 1$$

Page 64: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 64

10.2.2. File Test Expressions10.2.2. File Test Expressions

These occur in the expression part of These occur in the expression part of if-thenif-then and other control structures.and other control structures.

-d file-d file file file is a directoryis a directory

-f file-f file file file is a fileis a file

-e file-e file file file existsexists

-z file-z file file file is 0 bytes longis 0 bytes long

-r file-r file file file is readableis readable

-w file-w file writablewritable

-x file-x file executableexecutable

Page 65: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 65

10.2.3. Switch10.2.3. Switch

Format:Format:switchswitch (string variable) (string variable) case pattern: case pattern: commands commands breaksw breaksw case pattern: case pattern: commands commands breaksw breaksw : : default: default: commands commands breaksw breakswendswendsw

Page 66: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 66

ExampleExample

$ cat switch_1$ cat switch_1#!/bin/csh -f#!/bin/csh -f# See if first argument is yes or no. # See if first argument is yes or no. # Deal with a mix of upper and lower case.# Deal with a mix of upper and lower case.

# Does argv[1] exist?# Does argv[1] exist?if ($#argv == 0) thenif ($#argv == 0) then echo “Usage: switch_1 [yes | no]” echo “Usage: switch_1 [yes | no]” exit 1 exit 1endifendif

::

continued

Usage: $ switch_1 YeS Argument 1 is yes $

Page 67: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 67

switch ($argv[1])switch ($argv[1]) case [yY][eE][sS]: case [yY][eE][sS]: echo Argument 1 is yes echo Argument 1 is yes breaksw breaksw case [nN][oO]: case [nN][oO]: echo Argument 1 is no echo Argument 1 is no breaksw breaksw default: default: echo Argument 1 is neither yes or no echo Argument 1 is neither yes or no breaksw breakswendswendsw

Page 68: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 68

10.3. Looping10.3. Looping

10.3.1.10.3.1. ForeachForeach 10.3.2.10.3.2. WhileWhile

Page 69: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 69

10.3.1. foreach10.3.1. foreach

Format:Format:foreach loop-index (argument-list)foreach loop-index (argument-list) commands commandsendend

Page 70: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 70

Example 1Example 1 $ cat refname$ cat refname

#!/bin/csh -f#!/bin/csh -f# Usage: rename arg1 arg2# Usage: rename arg1 arg2### Changes the string arg1 to arg2 # Changes the string arg1 to arg2 # in the filenames of every file in # in the filenames of every file in # the current working directory.# the current working directory.

if ($#argv != 2) thenif ($#argv != 2) then echo Usage: refname arg1 arg2 echo Usage: refname arg1 arg2 exit 1 exit 1endifendif

::

continued

Usage: $ refname CPP C

Page 71: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 71

foreachforeach i (‘ls‘) i (‘ls‘) set newname = ‘echo $i | set newname = ‘echo $i | sedsed s/$1/$2/‘ s/$1/$2/‘ mv $i $newname mv $i $newnameendend

The text in ithat matches $1 ischanged to $2

VERY DANGEROUS

Page 72: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 72

$ cat foo-six$ cat foo-six#!/bin/csh -f#!/bin/csh -f# Assign up to 6 command line args # Assign up to 6 command line args # to the buffer array. Execute foo # to the buffer array. Execute foo # with buffer as its arguments# with buffer as its arguments

set buffer = (0 0 0 0 0 0)set buffer = (0 0 0 0 0 0)@ count = 1@ count = 1

if ($#argv > 6) thenif ($#argv > 6) then echo “Usage: foo-six [up to 6 args]” echo “Usage: foo-six [up to 6 args]” exit 1 exit 1endifendif

::

continued

Example 2Example 2 Usage: $ foo-six a b c

Page 73: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 73

foreachforeach arg ($argv[*]) arg ($argv[*]) set buffer[$count] = $arg set buffer[$count] = $arg @ count++ @ count++endend

echo There were $count argumentsecho There were $count argumentsexec foo $buffer[*]exec foo $buffer[*]exit 0exit 0

expands to $argv[0],$argv[1], etc.

expands to $buffer[0],$buffer[1], etc.

VERY DANGEROUS

Page 74: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 74

10.3.2. while10.3.2. while

Format:Format:while (expression)while (expression) commands commandsendend

Page 75: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 75

$cat while_1$cat while_1# Sum the numbers between 1 and # Sum the numbers between 1 and # the value in argv[1]# the value in argv[1]

@ limit = $argv[1]@ limit = $argv[1]@ index = 1@ index = 1@ sum = 0@ sum = 0

whilewhile ($index <= $limit) ($index <= $limit) @ sum += $index @ sum += $index @ index++ @ index++endend

echo The sum is $sum echo The sum is $sum

ExampleExampleUsage: $ while_1 20 The sum is 210

Page 76: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 76

10.4. Recursion10.4. Recursion

The script The script cppccppc visits every directory below visits every directory below the one supplied as its argument and renames the one supplied as its argument and renames any files ending with “any files ending with “.CPP.CPP” to end with “” to end with “.c.c””– e.g. e.g. foo.CPPfoo.CPP -->--> foo.cfoo.c

– usage:usage:$ cppc code/$ cppc code/

cppccppc could be implemented with could be implemented with findfind

Page 77: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 77

cppccppc#!/bin/csh -f#!/bin/csh -f# cppc “ replace all .CPP extensions with .c# cppc “ replace all .CPP extensions with .c

if ($#argv != 1) thenif ($#argv != 1) then echo “Usage: $0 directory” echo “Usage: $0 directory” exit(1) exit(1)endifendif

foreach file ($1/*) # files in directoryforeach file ($1/*) # files in directory if (-f $file) then if (-f $file) then if ($file:e == ‘CPP’) then if ($file:e == ‘CPP’) then mv $file $file:r.c mv $file $file:r.c echo Modifying $file to $file:r.c echo Modifying $file to $file:r.c endif endif else if (-d $file) then else if (-d $file) then $0 $file$0 $file # recursive call# recursive call endif endifendend

VERY DANGEROUS

Page 78: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 78

NotesNotes Pulling apart a filename that has an extension Pulling apart a filename that has an extension

(e.g. (e.g. foo.barfoo.bar))

$ set var = foo.bar$ set var = foo.bar

$ echo var:r$ echo var:r # # name without extensionname without extensionfoofoo

$ echo var:e$ echo var:e # just the extension# just the extensionbarbar

Page 79: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 79

A Standard ShapeA Standard Shape

Most recursive scripts have the following Most recursive scripts have the following 'shape':'shape':

foreach file ($1/*) # files in directoryforeach file ($1/*) # files in directory if (-f $file) then if (-f $file) then # do something to the file # do something to the file else if (-d $file) then else if (-d $file) then $0 $file$0 $file # recursive call# recursive call endif endifendend

Page 80: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 80

Title Words in Web filesTitle Words in Web files

The The wtitlewtitle script examines each “script examines each “.html.html” file in ” file in the directories below the one supplied as its the directories below the one supplied as its argument.argument.

If outputs the title words on each Web pageIf outputs the title words on each Web page– e.g e.g

if it sees:if it sees: <title>My Home Page</title><title>My Home Page</title>

then it prints:then it prints:MyMyHomeHomePagePage

Page 81: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 81

wtitlewtitle#!/bin/csh -f#!/bin/csh -f# wtitle: list the title words in HTML files# wtitle: list the title words in HTML files

if ($#argv != 1) thenif ($#argv != 1) then echo Usage: $0 directory echo Usage: $0 directory exit(1) exit(1)endifendif

foreach file ($1/*)foreach file ($1/*) if ((-f $file) && ($file:e == “html”)) then if ((-f $file) && ($file:e == “html”)) then grep -i title $file | \ grep -i title $file | \ awk -F\> ’{print $2}’ | \ awk -F\> ’{print $2}’ | \ awk -F\< ’{print $1}’ | \ awk -F\< ’{print $1}’ | \ tr ’ ’ ’\n’ | tr ’A-Z’ ’a-z’ tr ’ ’ ’\n’ | tr ’A-Z’ ’a-z’ else if (-d $file) then else if (-d $file) then $0 $file$0 $file # recursive call# recursive call endif endifendend

Page 82: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 82

NotesNotes grep -i title $filegrep -i title $file gets a gets a titletitle tag line: tag line:

<title>My Home Page</title><title>My Home Page</title>

awk -F\> ’{print $2}’awk -F\> ’{print $2}’ separates the line separates the line using ‘using ‘>>‘ and prints the second part:‘ and prints the second part:

My Home Page</title>My Home Page</title>

awk -F\< ’{print $1}’awk -F\< ’{print $1}’ separates the line separates the line using ‘using ‘<<‘ and prints the first part:‘ and prints the first part:

My Home PageMy Home Page

Page 83: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 83

UsageUsage $ wtitle caine/$ wtitle caine/

michaelmichaelcainecainecainecainepicturepicturecainecaine : :

$ wtitle caine/ | sort | uniq$ wtitle caine/ | sort | uniqcainecainemichaelmichaelpicturepicture : :

sorted and duplicates removed

Page 84: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 84

10.5. Interrupt Handling10.5. Interrupt Handling Not as good as BourneNot as good as Bourne

– only interrupt is supportedonly interrupt is supported– the control flow is hard to understandthe control flow is hard to understand– much improved in much improved in tcshtcsh

Format:Format:onintr labelonintr label

The script must have a line:The script must have a line:label:label:

Page 85: 240-491 Adv. UNIX:CShell/71 Advanced UNIX v Objectives of these slides: –introduce the C Shell –concentrate on features not in the Bourne Shell (but many.

240-491 Adv. UNIX:CShell/7 85

$ cat onintr_1$ cat onintr_1#!/bin/csh -f#!/bin/csh -f

onintr closeonintr close

while (1)while (1) echo Program is running. echo Program is running. sleep 2 sleep 2endend

close:close:echo End of Programecho End of Program

Usage: $ onintr_1 Program is running Program is running

::

End of Program

ctrl-Ctyped