'&$%CSE 303:Concepts and Tools for Software DevelopmentHal PerkinsAutumn 2008Lecture 4— Shell Variables, More Shell ScriptsCSE303 Autumn 2008, Lecture 4 1'&$%Where are WeWe understand most of the bash shell and its “programminglanguage”. Final pieces we’ll consider:• Shell variables– Defining your own– Built-in meanings– Exporting• Arrays• Arithmetic• For loopsEnd with:• A long list of gotchas (some bash-specific; some common to shells)• Why long shell scripts are a bad idea, etc.CSE303 Autumn 2008, Lecture 4 2'&$%Shell variablesWe already know a shell has state: current working directory, users,aliases, history.Its state also includes shell variables that hold strings.Features:1. Change variables’ values: foo=blah2. Add new variables: foo=blah or foo=3. Use variable: ${foo} (braces sometimes optional)4. Remove variables: unset foo5. See what variables “are set”: setOmitted feature: Functions and local variables (see manual)Roughly “all variables are global (visible everywhere)”Only (1) is similar to “re al” programming languagesCSE303 Autumn 2008, Lecture 4 3'&$%Why Variables?Variables are useful in scripts, just like in “normal” programming.“Special” variables affect shell operation. 3 most (?) c ommon:• PATH• PS1• HOMECSE303 Autumn 2008, Lecture 4 4'&$%ExportMinor point...If a shell runs another program (perhaps a bash script), does the otherprogram “see the current variables that are set”?• i.e., are the shell variables part of the initial environment of thenew program?It depends.export foo – yes it will see value of fooexport -n foo – no it will not see value of fooDefault is no.If the other program sets an exported variable, does the outer shell seethe change?No.CSE303 Autumn 2008, Lecture 4 5'&$%ArraysMore flexible than in Java, but much harder to use rightMake an array: foo=(x y z)Set element: foo[2]=hiGet element: ${foo[2]}Get number of elements: ${#foo[*]}Get all elements separated by spaces: ${foo[*]}Arrays do not have “fixed sizes”; e xample: code up an ever-growinglist.CSE303 Autumn 2008, Lecture 4 6'&$%ArithmeticVariables are strings, so k=$i+$j is not addition.But ((k=$i+$j)) is (and in fact the $ is optional).So is let k="$i + $j".The shell converts the strings to numbers, silently using 0 as necessary.Example: code up a stack. (Enough to reimplement built-ins pushdand popd.)CSE303 Autumn 2008, Lecture 4 7'&$%For-loopsSyntax:for v in w1 w2 ... wndobodydoneExecute body n times, with v set to wi on ithone. (Afterwards,v=wn).Why so convenient?• Use a filename pattern after in• Use list of argument s trings after in : "$@"• Use ${blah[*]} after inCSE303 Autumn 2008, Lecture 4 8'&$%Quoting and VariablesDoes x=* se t x to string-holding-asterisk orstring-holding-all-filenames?If $x is *, does ls $x list all-files or file named asterisk?Are variables expanded in double-quotes? single-quotes ?Could consult the manual, but honestly it’s easier to start a shell andexperiment. For e xample:x="*"echo xecho $xecho "$x" (Double quotes suppress some substitutions)echo ’$x’ (Single quotes suppress all substitutions)...CSE303 Autumn 2008, Lecture 4 9'&$%Gotchas: A very partial list1. Typo in variable name on left: create new variable oops=72. Typo in variable use: get em pty string ls $oops3. Use same variable name again: clobber other use HISTFILE=uhoh4. Omit subscript: get first element of array ${arr}5. Omit [*] on length: get 1st element’s string-length ${#arr}6. Array-out-of-bounds on left: create larger array7. Array-out-of-bounds on use: get empty string8. Spaces in variables: use double-quotes if you mean “one word”9. Non-number used as number: end up with 010. set f=blah: apparently does nothing (is assignment in csh)11. Omitted braces: $foo[0] and $12 not what you think.CSE303 Autumn 2008, Lecture 4 10'&$%Shell Programming RevisitedHow do Java programming and shell programming compare?The shell:• “shorter”• convenient file-access, file-tests, program-execution, pipes• crazy quoting rules and syntax• also interactiveJava:• none of the previous gotchas• local variables, m odularity, typechecking, array-checking, ...• real data structures, libraries, regular syntaxRough rule of thumb: Don’t write shell scripts over 200 lines?CSE303 Autumn 2008, Lecture 4 11'&$%Treatment of StringsSuppose foo is a variable that holds t he string helloJava BashUse variable (get hello) foo $fooThe string foo "foo" fooAssign variable foo = hi; foo=hiConcatenation foo + "oo" ${foo}ooConversion to number library-call silent and implicitMoral: In Java, variable-uses are easier than string-constants.Opposite in Bash.Both biased toward common use.CSE303 Autumn 2008, Lecture 4 12'&$%More on Sh ell ProgrammingMetapoint: Computer scientists automate and end up accidentallyinventing (bad) programming languages. It’s like using a screwdriveras a pry bar.HW2 in part, will be near the limits of what I recommend doing with ashell script (and we’ll end up cutting c orners as a result)There are plenty of attempts to get “the be st of both worlds” in ascripting language: Perl, Python, Ruby, ...Personal opinion: it raises the lim it to 1000 or 10000 lines? Get youhooked on short programs.Picking the bash shell was a c onscious decision to emphasize theinteractive side and see “how bad programming can get”.Next: Regular expressions, grep, sed, find.CSE303 Autumn 2008, Lecture 4 13'&$%Bottom LineNever do something manually if writing a script would save you time.Never write a script if you need a large, robust piece of software.Some programming languages try to give “best of both worlds” – younow have see n two e xtreme s t hat don’t (Java and bash).CSE303 Autumn 2008, Lecture 4
View Full Document