Lecture 6 Shell Programming Extension of Functionality n

  • Slides: 36
Download presentation
리눅스: Lecture 6 Shell Programming

리눅스: Lecture 6 Shell Programming

Extension of Functionality n UNIX is designed so that users can extend the functionality

Extension of Functionality n UNIX is designed so that users can extend the functionality n n To build new tools easily and efficiently To customize the shell and user interface. To string together a series of Unix commands to create new functionality. To create custom commands that do exactly what we want.

Shell Command Interpreter that turns text that you type (at the command line) in

Shell Command Interpreter that turns text that you type (at the command line) in to actions l User Interface: take the command from user l Ø Shell Programming Ø Ø Ø We often want to do a number of commands together And bundle them up into one new command. Just like a batch file in MS-DOS

Shell scripts Any collection of shell commands can be stored in a file called

Shell scripts Any collection of shell commands can be stored in a file called a shell script. Scripts have variables and flow control statements like other programming languages.

Popular Shells n Bourne Shell Korn Shell Bourne-Again Shell C Shell (for this course)

Popular Shells n Bourne Shell Korn Shell Bourne-Again Shell C Shell (for this course) n Shell scripts among those shells are slightly different sh n ksh n bash n csh, tcsh

shell script n Creating a simple shell script n A shell script is a

shell script n Creating a simple shell script n A shell script is a file that contains commands that the shell can execute. n n n Run a shell script n n n Any commands you enter in response to a shell prompt. n A utility n A compiled program n Another shell script Control flow commands Enter the script filename on the command line The shell interprets and execute the commands one after another Why shell script? n Simply and quickly initiate a complex series of tasks or a repetitive procedure.

Shell script example #!/bin/csh echo “Current Time - `date`” echo I am `whoami` C

Shell script example #!/bin/csh echo “Current Time - `date`” echo I am `whoami` C Shell

Invoking scripts There are two ways to launch scripts: 1) Direct interpretation csh scriptfile

Invoking scripts There are two ways to launch scripts: 1) Direct interpretation csh scriptfile [args …] 2) Indirect interpretation The first line of the file must be #!/bin/csh and the file must be executable (permission). C Shell

Shell Variables n Environment Variables n n (Global) environment variable n n Used to

Shell Variables n Environment Variables n n (Global) environment variable n n Used to provide information to programs New programs and shells inherit environment variables from their parent shell (Local) shell variable n n Used only by that shell Not passed to other processes

Environment Variables n “env” or “printenv” command n Display current environment variables n DISPLAY

Environment Variables n “env” or “printenv” command n Display current environment variables n DISPLAY The graphical display to use, e. g. nyssa: 0. 0 EDITOR The path to your default editor, e. g. /usr/bin/vi GROUP Your login group, e. g. staff HOME Path to your home directory, e. g. /home/frank HOST The hostname of your system, e. g. nyssa IFS Internal field separators, usually any white space (defaults to tab, space and <newline>) LOGNAME The name you login with, e. g. frank PATH Paths to be searched for commands, e. g. /usr/bin: /usr/ucb: /usr/local/bin PS 1 The primary prompt string, Bourne shell only (defaults to $) PS 2 The secondary prompt string, Bourne shell only (defaults to >) SHELL The login shell you're using, e. g. /usr/bin/csh TERM Your terminal type, e. g. xterm USER Your username, e. g. frank n n n

Set Shell Variables n Mostly set automatically when log in n setenv n n

Set Shell Variables n Mostly set automatically when log in n setenv n n $ setenv NAME value # in C Shell set n $ set name = value # in C Shell

Variables To set variables: set X [= value] # processed as a string To

Variables To set variables: set X [= value] # processed as a string To unset variables : unset X Variable contents are accessed using ‘$’: echo $PATH C Shell

Array To create lists: set Y = (abc 1 123) To set a list

Array To create lists: set Y = (abc 1 123) To set a list element: set Y[2] = 3 To view a list element: echo $Y[2] To count the number of variable elements: echo $#Y set fname = prog 1 rm ${fname}. c C Shell

Built-in Variables $user -- who am I? $path -- my execution path (list of

Built-in Variables $user -- who am I? $path -- my execution path (list of directories to be searched for executables) $term -- what kind of terminal I am using $status -- a numeric variable, usually used to retun error codes $prompt -- what I am currently using for a prompt $shell -- which shell am I using (usu. either /bin/csh or /bin/sh) % set Will display the variable lists.

Arithmetic (@) command C shell provides arithmetic operaters n must be used with the

Arithmetic (@) command C shell provides arithmetic operaters n must be used with the arithmetic (@) command n Arithmetic command works only with integers. n set count = 5 @ count += 2 echo $count 90

Shell Arithmetic n expr op 1 math-operator op 2 n Example % expr 1

Shell Arithmetic n expr op 1 math-operator op 2 n Example % expr 1 + 3 % expr 10 * 3 % set A = `expr 3 + $B`

Command arguments A shell script to swap files: #! cp cp cp rm /bin/csh

Command arguments A shell script to swap files: #! cp cp cp rm /bin/csh –f $argv[1] tempfile $argv[2] –f tempfile Arguments : $argv The number of arguments to a script: $#argv -f option says we want fast startup (no read. cshrc). C Shell

if-then-else if ( expr ) simple-command if ( expr ) then commandlist-1 [else commandlist-2]

if-then-else if ( expr ) simple-command if ( expr ) then commandlist-1 [else commandlist-2] endif C Shell

if-then-else cont’d An example: if ($#argv != 2) then echo “we need two parameters!“

if-then-else cont’d An example: if ($#argv != 2) then echo “we need two parameters!“ else set name 1 = $argv[1] set name 2 = $argv[2] endif C Shell

Loops while ( expr ) commandlist end foreach var ( worddlist ) commandlist end

Loops while ( expr ) commandlist end foreach var ( worddlist ) commandlist end C Shell

switch ( str ) case string 1: commandlist 1 breaksw case string 2: commandlist

switch ( str ) case string 1: commandlist 1 breaksw case string 2: commandlist 2 breaksw default commandlist endsw C Shell

goto (Considered harmful!) To jump unconditionally: goto label A label is a line such

goto (Considered harmful!) To jump unconditionally: goto label A label is a line such as: label: The classic paper on why not to use goto: Go To Statement Considered Harmful Edsger W. Dijkstra, CACM, March 1968 C Shell

shift command n Moves the values in the parameters toward the beginning of the

shift command n Moves the values in the parameters toward the beginning of the parameter list #!/bin/csh –f echo “There are” $#argv “parametersn” while ($#argv > 0) echo –n “$argv[1] “ shift end echo “n” echo “There are now” $#argv “parameters” echo “end of script” C Shell

Input n Reading Line by Line % set x = $< This is a

Input n Reading Line by Line % set x = $< This is a line. % echo $x This is a line.

File Operators -e -r -l -w -x -o -f -d -s -z file file

File Operators -e -r -l -w -x -o -f -d -s -z file file file : : : : : True True True if if if file exists file is readable file exists and is a symbolic link file exists and is writable file exists and is executable the user owns it the file exists and is a regular file the file exists and is a directory file exists and has a size greater than zero file length is zero (empty)

Logical operator ! : NEGATE n && : logical AND n || : logical

Logical operator ! : NEGATE n && : logical AND n || : logical OR n n Ex) if (! -e somefile) then # does not exist

Debugging %csh –vx somescript args -v : vervose -x : echoes the commands after

Debugging %csh –vx somescript args -v : vervose -x : echoes the commands after all substitutions are made -n : syntax check. No execution

example #!/bin/csh if (-e $argv[1]) then echo $argv[1] exists else echo $argv[1] does not

example #!/bin/csh if (-e $argv[1]) then echo $argv[1] exists else echo $argv[1] does not exist and cannot be opened endif # rest of script here C Shell

example #!/bin/csh set sum = 0 echo –n “Enter a number: set num =

example #!/bin/csh set sum = 0 echo –n “Enter a number: set num = $< ” while ($num != “”) @ sum += $num echo –n “Enter the next number: ” set num = $< end echo “n. The sum of the number is : $sum” C Shell

Guidelines n Shell script is better than C program if the problem can be

Guidelines n Shell script is better than C program if the problem can be solved by using UNIX commands n Why script? n n n Easier to create and modify Easy to debug Good thing to do n n Use redirection and pipe Do validity check (argument number , type) Check existence of files and directories Display error messages

example #!/bin/csh set j = (1 2 3 4 5) foreach i ($j) echo

example #!/bin/csh set j = (1 2 3 4 5) foreach i ($j) echo $i Hello end C Shell

example #!/bin/csh set ary = `cat ary. dat` echo “The C Shell whole array

example #!/bin/csh set ary = `cat ary. dat` echo “The C Shell whole array : $ary” number of elements : $#ary” first element: $ary[1]” last element: $ary[$#ary]”

Numeric validation example #!/bin/csh echo $argv[2] > temp grep ‘^[0 -9]*$’ temp > /dev/null

Numeric validation example #!/bin/csh echo $argv[2] > temp grep ‘^[0 -9]*$’ temp > /dev/null if ($status != 0) then echo “Month argument is not numeric” exit 1 endif if ($argv[2] < 1 || $argv[2] > 12) then echo “Month argument must be <1… 12>” exit 2 endif echo “Validation is OK. We continue. ” C Shell

example #! /bin/csh -f foreach name ($argv) if ( -f $name ) then echo

example #! /bin/csh -f foreach name ($argv) if ( -f $name ) then echo -n "delete the file '${name}' (y/n/q)? " else echo -n "delete the entire dir '${name}' (y/n/q)? " endif set ans = $< # $< means “read a line” switch ($ans) case n: continue case q: exit case y: rm -rf $name continue endsw end: C Shell

Exercise 1 n Write a shell script that displays the number of files and

Exercise 1 n Write a shell script that displays the number of files and directories in a given directory n format %. /fd_count. csh directory_name

Exercise 2 n Write a shell script that removes duplicate words from an input

Exercise 2 n Write a shell script that removes duplicate words from an input text file. n Format n % remove_dup. csh in. txt out. txt Four Two One Four Two Three Four Two One Three out. txt in. txt