1 / 99

Advanced UNIX

Advanced UNIX. 240-491 Special Topics in Comp. Eng. 1 Semester 2, 2000-2001. Objectives explain how to write Bourne and Bash Shell scripts. 6. The Bourne and Bash Shells. Overview. 1. Making a File Executable 2. Combining Commands 3. Redirecting Output 4. Executing Scripts

savea
Télécharger la présentation

Advanced UNIX

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. Advanced UNIX 240-491 Special Topics in Comp. Eng. 1Semester 2, 2000-2001 • Objectives • explain how to write Bourne and Bash Shell scripts 6. The Bourne and Bash Shells

  2. Overview 1. Making a File Executable 2. Combining Commands 3. Redirecting Output 4. Executing Scripts 5. Variables 6. Control Flow continued

  3. 7. Functions 8. Other Commands 9. Here Documents 10. Debugging 11. More Information

  4. 1. Making a File Executable • $ cat whosondateecho Users currently logged onwho • Wrong: $ whosonwhoson: Permission denied

  5. Right: • $ ls -lg whoson-rw-r--r-- 1 ad pubs 42 Jun 17 10:55 whoson$ chmod u+x whoson$ ls -lg whoson-rwxr--r-- 1 ad pubs 42 Jun 17 10:55 whoson • $ whosonTue Nov 7 13:21:34 ICT 2000Users currently logged inad consol Nov 7 08:26jenny tty02 Nov 7 10:04

  6. Possible PATHProblem • $ whosonwhoson: Command not found • Due to PATHshell variable (see later) • Quick fixes:$ ./whosonor $ sh whoson

  7. 2. Combining Commands • Sequencing: $ a ; b ; c • same as: $ a $ b $ c

  8. Process Creation (&) • $ a & b & c14271 (PID for a)14272 (PID for b) • $ a & b & c &142901429114292$ • $ a | b | c &14302 (PID for piped commands)

  9. Processes in Action $ cat aecho -n “aaaaaaaaaaaaaaaaaaaaa”echo -n “aaaaaaaaaaaaaaaaaaaaa”sleep 2echo -n “aaaaaaaaaaaaaaaaaaaaa”echo -n “aaaaaaaaaaaaaaaaaaaaa” • Similarly for b and c • Try the following a few times: $ a & b & c & On calvin there isn't much variation unless the machine is loaded.

  10. 3. Redirecting Output • 1> redirect standard output (stdout)2> redirect standard error (stderr) $ cat a b 1> out 2> err Files stdout out cat a b err stderr

  11. >& • redirect one stream into another: • 2>&1 redirect stderr into stdout $ cat a b 1> theLot 2>&1 stdout theLot cat a b stderr

  12. 4. Executing Scripts • Make sure that a script is executed by the Bourne Shell: $ sh whoson(no need for chmod) • or: $ cat boss#!/bin/shecho Definitely Bourne Shell Script continued

  13. On Linux machines (e.g. calvin), the Bourne shell has been replaced by Bash • sh means the Bash shell

  14. 5. Variables 5.1. User-defined Variables 5.2. Environment Variables 5.3. Readonly Shell Variables

  15. 5.1. User-defined Variables No spaces around the = • $ person=alex$ echo personperson$ echo $personalex • $var returns the value stored in var • called substitution

  16. 5.1.1. Switch off Substitution • Swich off substitution with 'var' or \var • $ echo '$person'$person$ echo \$person$person

  17. 5.1.2. Switch off Special Chars (") • "" switches off the special meaning of characters used in filename generation (e.g. *, ?) • $ ls // directory contentsad.reportad.summary • $ memo=ad*$ echo "$memo"ad*$ echo $memoad.report ad.summary * means only * * means any number of characters

  18. 5.1.3. Exporting Variables • Normally a variable is local to the running script (the process). • It is sometimes useful if running scripts (processes) can access another script’s variables. • e.g. we want to use cheese in subtest calls extest subtest cheese=english

  19. No Exporting: extest1& subtest Using " is a good habit, see later • $ cat extest1cheese=englishecho "extest1 1: $cheese"subtestecho "extest1 2: $cheese"$cat subtestecho "subtest 1: $cheese"cheese=swissecho "subtest 2: $cheese" continued

  20. subtest does not see extest1's cheese value • $ extest1extest1 1: englishsubtest 1: subtest 2: swissextest1 2: english extest1 is not affected by subtest's setting of cheese

  21. Exporting: extest2& subtest • $ cat extest2export cheesecheese=englishecho “extest2 1: $cheese”subtestecho “extest2 2: $cheese” • $ extest2extest2 1: englishsubtest 1: englishsubtest 2: swissextest2 2: english cheese value passed in change not exported from subtest

  22. 5.1.4. Reading read inputs everything up to the newline • $ cat readlnecho -n “Type: ”read lnecho “You entered: $ln” • $ readlnType: The Wizard of OzYou entered: The Wizard of Oz

  23. No Quotes • $ cat readlnnqecho -n “Type: ”read lnecho You entered: $ln • $ lsad.report summary1$ readlnnqType: *You entered: ad.report summary1 directory contents

  24. 5.1.5. Executing Commands A very simple shell • $ cat proc_cmdecho -n “Enter a command: ”read command$commandecho Thanks • $ proc_cmdEnter a command: echo Display thisDisplay thisThanks

  25. 5.1.6. Splitting Input Text is split based on white space. • $ cat split3echo -n “Enter something: ”read word1 word2 word3echo “Word 1 is: $word1”echo “Word 2 is: $word2”echo “Word 3 is: $word3” • $ split3Enter something: this is somethingWord1 is: thisWord2 is: isWord3 is: something

  26. $ split3Enter something: this is something else, xWord1 is: thisWord2 is: isWord3 is: something else, x The last variable gets everything that is left in the input.

  27. 5.1.7. Command Subsitution Must use ‘ • $ cat mydirthis_dir=‘pwd‘echo “Using the $this_dir directory.”this_date=$(date)echo "Today's date: $this_date" • $ mydirUsing /home/ad/teach/adv-unix/bourne directoryToday's date: Tue Nov 7 13:52:46 ICT 2000$ A Bash addition

  28. 5.2. Environment Variables • Most environment variables get their values from the shell at login. • The values of some of the variables can be set by editing the .profile file in your home directory • Bash uses .bash_profile and .bashrc

  29. 5.2.1. Examples • HOME pathname of your home directory • $ pwd/home/ad/planning$ echo $HOME/home/ad$ cd$ pwd/home/ad cd uses HOME to return to your home directory continued

  30. PATH • directories where executable can be found • represented as a string of pathnames separated by ‘:’s • $ echo $PATH/usr/local/bin:/usr/bin:/bin:$ PATH=SPATH":/home/ad/bin:."$ echo $PATH/usr/local/bin:/usr/bin:/bin:/home/ad/bin:. Extend the default PATH

  31. Note for SysAdmins • If you are the system administrator (superuser, root) for your machine, do not extend your path with "." • it opens you to potential attack by hackers • e.g. 'fake' UNIX utilities placed in the current directory

  32. 5.2.2. Typical .profile • $ cat .profileTERM=vt100PATH=$PATH":/home/ad/bin:."PS1=“ad: “CDPATH=:$HOMEexport TERM PATH PS1 CDPATHstty kill ^u • $ . .profile export needed in the Bourne shell

  33. 5.2.3. Typical .bash_profile • On calvin, .bash_profile simply invokes your .bashrc (if it exists): umask 002if [ -f ~/.bashrc -a PS1="\$ " ]; then . ~/.bashrcfi These shell commands will be explained later continued

  34. Typical .bashrc • PS1="\u@\h$ "# PS1="\w[\#]$ "PATH=$PATH":."alias ls='/bin/ls -F'alias dir='ls -ba'alias cls="clear" : :psgrep(){ ps aux | grep $1 | grep -v grep} No export needed These features will be explained later.

  35. 5.2.4. set • The current settings for the environment variables can be listed with set: $ set | moreBASH=/bin/bash :PATH=/usr/local/bin:/usr/bin:/bin:. :PS1='\u@\h$ ' :

  36. 5.3. Readonly Shell Variables • These are environment variables that cannot have their values changed. • Most of them relate to the arguments supplied to a script when it is called.

  37. 5.3.1. Script Name ($0) • $ cat abcecho The name of this script is $0 • $ abcThe name of this script is abc

  38. 5.3.2. Script Arguments ($1, $2,..., $9) • $ cat display_5argsecho The first five command lineecho arguments are $1 $2 $3 $4 $5 • $ display_5args jenny alex helenThe first five command linearguments are jenny alex helen If the variable has no value, then nothing is printed.

  39. 5.3.3. All Arguments ($*) • $ cat display_allecho $* • $ display_all a b c de fg hi jk mno pqr stu w x y za b c de fg hi jk mno pqr stu w x y z • $@is like $* but puts “...” around each printed argument

  40. 5.3.4. Number of Arguments ($#) • $ cat num_argsecho “This script has $# arguments.” • num_args helen alex jennyThis script has 3 arguments

  41. 5.3.5. The shiftCommnd • shiftmoves argument values on the command line one $<number> to the left. • Overcomes limit of 9 argument variables($1, $2, ..., $9) continued

  42. $ cat demo_shiftecho “arg1= $1 arg2= $2 arg3= $3”shiftecho “arg1= $1 arg2= $2 arg3= $3”shiftecho “arg1= $1 arg2= $2 arg3= $3”shift • $ demo_shift alice helen jenny junearg1= alice arg2= helen arg3= jennyarg1= helen arg2= jenny arg3= june arg1= jenny arg2= june arg3= jenny "moves" to the left.

  43. 5.3.6. The setCommand (Again) • set ‘cmd‘ (must use ‘) • evaluates cmd and assigns its values to the script command line arguments ($1, $2, ..., $9, $*) • the values in cmd output are separated by whitespace continued

  44. $ dateFri Jun 17 23:04:09 GMT+7 1996$ cat datesetset ‘date‘echo $*echoecho “Argument 1: $1”echo “Argument 2: $2”echo “Argument 3: $3”echo $2 $3, $6 The date values are assigned to $1, $2, etc. continued

  45. $ datasetFri Jun 17 23:04:13 GMT+7 1996Argument 1: FriArgument 2: JunArgument 3: 17Jun 17, 1996

  46. 6. Command Flow 6.1. Branching 6.2. Test Forms 6.3. Looping 6.4. break, continue, : 6.5. trap

  47. 6.1. Branching • $ cat same_wordecho -n “word 1: ”read word1echo -n “word 2: ”read word2if test "$word1" = "$word2"then echo Matchfiecho End of Program Use " to stop filename expansion continued

  48. $ same_wordword1: peachword2: peachMatchEnd of Program

  49. 6.1.1. Second Format Redirect stdout to stderr • $ cat chkargsif [ $# = 0 ]then echo Usage: chkargs argument... 1>&2 exit 1fiecho Program runningexit 0 • $ chkargsUsage: chkargs argument...$ chkargs abcProgram running

  50. 6.1.2. if-then-else C programmers prefer this format • $ cat showif [ $# = 0 ]; then echo Usage: show [-v] filenames 1>&2 exit 1fiif [ “$1” != “-v” ]then cat “$@”else shift more “$@”fi Use: $ show -v f1.txt f2.txt

More Related