990 likes | 1.18k Views
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
E N D
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
Overview 1. Making a File Executable 2. Combining Commands 3. Redirecting Output 4. Executing Scripts 5. Variables 6. Control Flow continued
7. Functions 8. Other Commands 9. Here Documents 10. Debugging 11. More Information
1. Making a File Executable • $ cat whosondateecho Users currently logged onwho • Wrong: $ whosonwhoson: Permission denied
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
Possible PATHProblem • $ whosonwhoson: Command not found • Due to PATHshell variable (see later) • Quick fixes:$ ./whosonor $ sh whoson
2. Combining Commands • Sequencing: $ a ; b ; c • same as: $ a $ b $ c
Process Creation (&) • $ a & b & c14271 (PID for a)14272 (PID for b) • $ a & b & c &142901429114292$ • $ a | b | c &14302 (PID for piped commands)
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.
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
>& • redirect one stream into another: • 2>&1 redirect stderr into stdout $ cat a b 1> theLot 2>&1 stdout theLot cat a b stderr
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
On Linux machines (e.g. calvin), the Bourne shell has been replaced by Bash • sh means the Bash shell
5. Variables 5.1. User-defined Variables 5.2. Environment Variables 5.3. Readonly Shell Variables
5.1. User-defined Variables No spaces around the = • $ person=alex$ echo personperson$ echo $personalex • $var returns the value stored in var • called substitution
5.1.1. Switch off Substitution • Swich off substitution with 'var' or \var • $ echo '$person'$person$ echo \$person$person
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
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
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
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
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
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
No Quotes • $ cat readlnnqecho -n “Type: ”read lnecho You entered: $ln • $ lsad.report summary1$ readlnnqType: *You entered: ad.report summary1 directory contents
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
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
$ 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.
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
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
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
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
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
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
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
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.
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$ ' :
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.
5.3.1. Script Name ($0) • $ cat abcecho The name of this script is $0 • $ abcThe name of this script is abc
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.
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
5.3.4. Number of Arguments ($#) • $ cat num_argsecho “This script has $# arguments.” • num_args helen alex jennyThis script has 3 arguments
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
$ 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.
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
$ 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
$ datasetFri Jun 17 23:04:13 GMT+7 1996Argument 1: FriArgument 2: JunArgument 3: 17Jun 17, 1996
6. Command Flow 6.1. Branching 6.2. Test Forms 6.3. Looping 6.4. break, continue, : 6.5. trap
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
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
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