170 likes | 335 Views
CS 497C – Introduction to UNIX Lecture 34: - Shell Programming. Chin-Chih Chang chang@cs.twsu.edu. Sample Scripts. The script cpback.sh shown in Fig. 18.1 protects your files from accidental overwritting by the cp command.
E N D
CS 497C – Introduction to UNIXLecture 34: - Shell Programming Chin-Chih Changchang@cs.twsu.edu
Sample Scripts • The script cpback.sh shown in Fig. 18.1 protects your files from accidental overwritting by the cp command. • The script dentry1.sh shown in Fig. 18.2 accepts a code and its corresponding description from the terminal, performs some rudimentary validation checks, and then adds an entry to a file desig.lst. • The continue statements let you reenter the data or start a fresh cycle.
Sample Scripts • The break statement in the inner loop quits the loop after adding the line. • You should use “$@” with a for loop when using multiword arguments. for file in “$@” • basename is a command to strip directory and suffix from filenames $ basename hello.java .java hello
Sample Scripts • You can use basename inside a for loop to change the extensions of files. for file in *.txt ; do leftname=`basename $file .txt` mv $file ${leftname}.doc done • The cpback2.sh script accepts multiple filenames and backup them without overwritting.
The Here Document (<<) • The here document (<<) provides input to a script from the script itself. • It can be used with both command substitution and variables. • It is often used with commands that don’t use a filename as argument or for running interactive programs noninteractively. mail cs497c << EOF Test Date is `date`. EOF
let: Computation – A Second Look (ksh and bash) • Some advanced features of shell programming only happen in Korn and bash shell. • Korn shell is located in /usr/bin/ksh. Bash shell is located in /bin/bash. • You can compute with let statement: $ let sum=256+128; echo $sum • There is no space after variable. If you need space, just quote the expression:
let: Computation $ let sum=“3 * 6 + 4 / 2”; echo $sum $ x=22 y=28 z=5; z=$((x+y+z)); echo $z • When a process is created by the shell, it makes certain features of its own environment to the child. • The created process make use of the inherited parameters including: • The PID of the parent process. • The UID (owner) and GUID (group owner) of the process.
Sub-Shells • The current working directory. • The three standard files. • Other open files used by the parent process. • Some environment variables available in the parent process. • A variable defined in the parent is visible in the child only when it is exported (export). • However, when the child alters the value of the variable, the changed value is not seen by the parent.
Sub-Shells & Arrays • The matching operators () run a group of commands in a sub-shell, but the {} don’t spawn one. • Korn and bash support one-dimensional arrays where the first element has the index 0. $ prompt[2]=“Enter your name” $ echo ${prompt[2]}
Arrays • You can use a space-delimited list enclosed with parentheses: month_arr=(0 31 28 31 30 31 30 31 31 30 31 30 31) $ echo ${month_arr[6]} • In the older version of Korn, you can use the set –A statement: set –A mon_arr 0 31 28 31 30 31 30 31 31 30 31 30 31 • Using the @ or * as subscript, you an display all the elements of the array as well as the number of elements.
Arrays & String Handling $ echo ${month_arr[@]} $ echo ${#month_arr[@]} • The dateval.sh script in Fig. 19.2 use arrays to validate an entered date. • The length of string can be found by preceding the variable name with a #. $ name=“Jay Leno”; echo ${#name} • You can extract a substring: $ echo ${name:4:4}
Conditional Parameter Substitution • Shell variables can be evaluated in a conditional manner depending on whether they are assigned a non-empty value. This is called parameter substitution with the following format: ${variable:symbol string} where symbol can be +, -, = or ?. • When the + option is used, variable is evaluated to string if it has a non-null value.
Conditional Parameter Substitution found=`ls`; echo ${found:+“Files found."} • When - option is used, variable is evaluated to string if it has a null value. • The = operator additionally assigns a value to the variable. while [${x:=1} -le 10] • The ? option prints an error message and exits the shell. grep $pattern ${flname:?”No file .. quitting”}
Shell Functions • A shell function consists of a group of statements that are executed together as a bunch. • Optionally, it also returns a value: function_name() { statements return value } • mainfunc.sh displays some functions.
Shell Functions anymore() { echo $option "\n$1 ?(y/n) : \c" 1>&2 read response case "$response" in y|Y) echo 1>&2 ; return 0 ;; *) return 1 ;; esac } $ anymore “Wish to continue”
eval & exec • eval processes a command line twice and is used to simulate arrays and execute. • With eval, you can create generalized numbered prompts and variables that significantly compact code. $ prompt1=“User Name:” $ x=1; eval echo \$prompt$x • exec overlays the current shell when prefixed to a command.
exec & trap $ exec date • To debug shell scripts, use set –x at the beginning of the script so that every command line is echoed to the screen. • Use trap if you want your script to respond to an interrupt in a specific way. trap ‘command_list’ signal_list • It is useful in removing temporary files when a script receives a signal.