1 / 30

Unix Comp-145

Unix Comp-145. Lecture 8: Shell Programming Based on: S. Das, “Your Unix: The ultimate Guide”, 2 nd Edition, McGraw Hill, 2006 (Chapter 13). Shell Programming. Processing Flow Control in Shell Scripts Loop Execution in Shell Scripts Arithmetic Comparative Tests in Shell Scripts

baka
Download Presentation

Unix Comp-145

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Unix Comp-145 Lecture 8: Shell Programming Based on: S. Das, “Your Unix: The ultimate Guide”, 2nd Edition, McGraw Hill, 2006(Chapter 13) BROOKDALE COMMUNITY COLLEGE

  2. Shell Programming Processing Flow Control in Shell Scripts Loop Execution in Shell Scripts Arithmetic Comparative Tests in Shell Scripts Debugging Shell Scripts Concepts in Shell Program Design Techniques BROOKDALE COMMUNITY COLLEGE

  3. Naming Shell Scripts • Script name is arbitrary • Choose names that make it easy to quickly identify file function • Using .shas an extension to denote shell script files doesn't make the script executable • Example: quartery_report.sh • Use chmod +x to make shell script executable • To execute in current directory use ./script.sh if script.shhas u=rwx BROOKDALE COMMUNITY COLLEGE

  4. Scripting Internals Make Script Interactive: Read Enables script to take input from user. Make script Non-Interactive: Pipes and Redirection Use positional parameters Parameter values input from Command Line when launched In script input variables referred to a %1, %2, etc # indicates characters to its right on this line is to be ignored, i.e., a comment BROOKDALE COMMUNITY COLLEGE

  5. Scripting Internals • Interactive Script example: • $ echo “Enter pattern to be searched: \c”# \c = no newline • $read var1 • $ echo “Enter file to be used: \c” • $read var2 • $echo “Searching for $var1 from file $var2” • $grep “$var1” $var2 • Non-Interactive Script example: • $ echo “Program: $0”# $0 always = script name • $ echo “The number of arguments specified is $#” • $ echo “The arguments are $*” # all arguments stored in $* • $ grep “$1” $2 • $ echo “\nJob Over” BROOKDALE COMMUNITY COLLEGE

  6. Scripting Internals • Exit status • Exit - default value is 0 • Exit 0 - True, everything OK • Exit 1 - False, error encountered • $? - Stores EXIT status of last command • Writer of script determines semantics of success • Example, Not Found could be exception or desired result BROOKDALE COMMUNITY COLLEGE

  7. Scripting Internals: Logical Operators • Operators && and || recommended for simple decisions • cmd1&&cmd2 # cmd2 executed if cmd1 succeeds • cmd1||cmd2 # cmd2 executed if cmd1 fails • Examples: • $ grep ‘manager’ foobar || echo “Pattern not found” • $ grep “$1” $2 || exit 2 # Quit script if search fails • $ echo “Patern found, Job over” #executed only if grep succeeds BROOKDALE COMMUNITY COLLEGE

  8. Scripting Internals: Logical Operators • If, then, else conditional constructs – Tests command exit status– if requires a then and fi ending – if ! Command- Test is NOT true or successful C. A. • if command is true # successful? • then • excute commands • else • fi • if command is true # successful? • then • excute commands • elifcommand is true • then • excute commands • else • excute commands • fi B. • if command is true # successful? • then • excute commands • else • excute commands • fi D. • if command is true; then • ... • fi BROOKDALE COMMUNITY COLLEGE

  9. Scripting Internals: Logical Operators • Example from text • $ pico ifthen.sh • if grep “[: ]$1[: ]” /etc/passwd# successful? • then • echo “Pattern found – Job over” • else • echo “Pattern not found” • fi • $ chmod 744 ifthen.sh • $ ifthen.sh Mensing BROOKDALE COMMUNITY COLLEGE

  10. Scripting Internals: Logical Operators • Usingtestand[ ]to evaluate expressions inconditional constructs – Relational Tests • test returns exit status only - use with constructs that can operate on an exit status. • Compare 2 numbers • test $x –gt $y • Compare 2 strings or a single string for a null value • test $x != $y OR • if [!-n “$option”] • Check a file’s attributes • if [-f !-r $1]; then BROOKDALE COMMUNITY COLLEGE

  11. Scripting Internals: Logical Operators • Compare 2 numbers • -eqEqual to • -neNot Equal to • -gtGreater than • -geGreater or equal to • -ltLess than • -leLess or equal to • Example: • $ x=5; y=7; z=7.4 • $ test $x –eq $y; echo $? • $ 1 -- test returns not true BROOKDALE COMMUNITY COLLEGE

  12. Scripting Internals: Logical Operators • Compare 2 strings • =Equal to • !=Not Equal to • -n stringString not NULL • -z stringString is a NULL string • StringString is assigned and not NULL • ==Strings equal? (only in Korn and Bash Shell) • Example: • $ if [“$option” = “y”]; then #tests input equality • $if [-z “$option”]; then #tests input for NULL string BROOKDALE COMMUNITY COLLEGE

  13. Scripting Internals: Logical Operators • File attribute tests -- see table 13.4 for full list • -f fNamefName exist and is a regular file? • -r fNamefName exist and is readable? • -x fNamefName exist and is readable? • -s fNamefName exist and is its size greater than 0? • !-s fNamefName exist and is its size not greater than 0? • Example: • if [-s $1]; then #tests input file exists and size > 0 BROOKDALE COMMUNITY COLLEGE

  14. Scripting Internals: Logical Operators • Using if and test in Compound Conditions – 2 forms • Using && and || together with other operators • if [“$0” = “lm”]||[“$0” = “./lm”]; then • Using -aand -o together with other operators • if [“$0” = “lm”] -o [“$0” = “./lm”]; then BROOKDALE COMMUNITY COLLEGE

  15. Scripting Internals: Case Conditional • Using case statements (instead of if,then,else) • Tests the value of an expression with each alternative • Uses a construct to match a pattern with a list of alternatives • Pattern can use a number, string with logical OR “|” or asterisk or a range, e.g., y|Y)or*)or1) ora) or[A-Z]) or[A-Za-z]) or *[0-9]*) • Each alternative associated with specific action • Expression can be a variable entered by user • Each pattern line must end with ;; • Each case sequence must end with easc BROOKDALE COMMUNITY COLLEGE

  16. Scripting Internals: Case Conditional • Generic format • case expression in • pattern1) commands1 ;; • pattern2) commands2 ;; • pattern3) commands3 ;; • . . . • patternn) commandsn ;; • esac BROOKDALE COMMUNITY COLLEGE

  17. Scripting Internals: Case Conditional • Example: • # Use of a case statement to offer a 5 item menu • echo “ Menu\n1. List of files \n2. Processes of user\n3. Today’s date • 4. Users of system\n5. Quit to Unix\nEnter your option #: \c” • read choice • case “$choice” in • 1) ls -l;; • 2) ps -f;; • date;; • who ;; • exit ;; • *) echo “Invalid option”# ;; not needed for last option • esac BROOKDALE COMMUNITY COLLEGE

  18. Scripting Internals: For/While/Until Loops • Lets a set of instructions be repeated while a condition exists • do and done delimit the loop body • Source values for list in forloop is your choice – fileName, variable • for variable in list • do • commands • done • for var in $PATH $HOME • while condition is true • do • commands • done BROOKDALE COMMUNITY COLLEGE

  19. Scripting Internals: For/While/Until Loops • Example: create a backup copy of each file named in a list • List can use wild-card, e.g., chapt2* • $ for f1in chapt20 chap21 chap22 ; do • > cp $f1 ${f1}.bak • > Echo $f1 copied to $f1.bak • > done NOTE: White space separates members of list, however white spaces in quotes are treated as one word in the list , e.g., q4 q5 q6 “q7 87” BROOKDALE COMMUNITY COLLEGE

  20. Scripting Internals: For/While/Until Loops • while / do loop – Towait a while, and then execute the command again, OR execute a command indefinitely OR use to execute a finite number of times. • Example: run a command 5 times • Decrement or increment the value of variable “x” each iteration of the loop • $ x=5 • $ while [ $x –gt 0 ] ;do • > ps –e ; sleep 3 • > x=`expr $x - 1` • > done BROOKDALE COMMUNITY COLLEGE

  21. Arithmetic Options: Computation with expr • expr :: 4 basic arithmetic operations on numbers • Add, subtract, multiply, divide • Escape multiply sign \* • $ x=3; y=5 • $ expr 3 + 5 # simple sum using numbers • $ expr $x - $y # simple difference using variables • $ expr $x \* $y # escape the astrisk • $ expr $y / $x # decimal truncated • $ z=`expr $x \* $y`; echo $z # create new variable BROOKDALE COMMUNITY COLLEGE

  22. Arithmetic Options: Computation with expr • expr :: to validate length of or extract strings • Uses 2 expressions separated by a colon • Determine length of string: • $ expr “robert_kahn” : ‘.*’ # white space around : • Validate length of string: • if [ `expr “$name” : ‘.*’` -gt 20 ]; then BROOKDALE COMMUNITY COLLEGE

  23. Shell Functions • Executes a group of statements enclosed within { } • Function name identified with () after the string indicating a NULL argument list • functionName() { • statements • return value# value is a number • } BROOKDALE COMMUNITY COLLEGE

  24. Debuging Shell Scripts: Shell Functions • 1. Command line example with return value supporting positional parameters: • $ anymore() { • > echo “$1 ?(y/n) : \c” 1>&2 > read input • > case “$input” in • > y|Y) echo 1>&2; return 0 ;; • > *) return 1 ;; • > esac • > } • 2. Command line example: • $ ll() { • > ls –l $* | more • > } BROOKDALE COMMUNITY COLLEGE

  25. Debugging Shell Scripts: DEBUG Function • Most basic way is to use command set • set -overbose • set –o xtrace • verboseEchoes each command before running them tostderr • xtraceEchoes each command after command-line processing, after parameter and command substitution, and the other subsequent steps. • Starts each line it prints with + which is customizable through the built-in shell variablePS4. So you can set PS4to "xtrace-> " BROOKDALE COMMUNITY COLLEGE

  26. Debugging Shell Scripts: DEBUG Function • Other ways: • UsePS4='$0 line $LINENO: ‘ to display the file name and line number • UsePS4= “xtrace-> ”to change the indicator • If code debugging calls other functions defined elsewhere, use the same way with an option to the typeset command. To trace the named function (fnName) whenever it runs, Enter the command in the shell that calls it typeset -ftfnName, # f = fn, t = trace BROOKDALE COMMUNITY COLLEGE

  27. Shell Program Design Techniques:Basics of Script Writing • Writing any script involves these steps: • Run the UNIX command interactively at a shell prompt. • Create the shell script containing UNIX command and Shell constructs. • Make the shell script executable. • Test the script. • Launch the script. • Interactively • Once, at a future date and time • Repeatedly on a fixed schedule • Employ a convention for naming & storing scripts BROOKDALE COMMUNITY COLLEGE

  28. Shell Program Design Techniques:Basics of Script Writing • Script Writing Tips: • Start scripts with a comment line that explains the script’s purpose. • Use uppercase when defining variables. Use underscores ( _ ) to separate words. • Export environment variables to provide any sub-processes with automatic access to the values. BROOKDALE COMMUNITY COLLEGE

  29. Shell Program Design Techniques:Basics of Script Writing • Script Writing Tips (cont’d): • To use the output of a UNIX command elsewhere in script, type a $, enclose the command within parentheses (), and store the output in an environment variable, e.g., VAR1=$(command1|command2) • To use a value of an environment variable, put a $ in front of the variable name and to avoid ambiguities, enclose the variable name inside curly braces {} • When running a script from the current directory, precede a script name with dot-slash (./) to instruct the shell to look in the current directory BROOKDALE COMMUNITY COLLEGE

  30. Shell Program Design Techniques:Basics of Script Writing • Script Writing Tips (cont’d): • Redirectstderr, either to the same destination as stdoutor to a unique file • Redirectstdout ( >) to a file, or appendstdout ( >> ) to a file • Use the for-loop or while loop or case loop to process a list of things BROOKDALE COMMUNITY COLLEGE

More Related