Fun with Control Structures in Shell Scripting
330 likes | 652 Views
This chapter covers control structures in BASH shell scripting, including file descriptors, variables, tests, logical expressions, syntax examples, and loops. Learn about if-then, if-then-else, if-then-elif structures, case statements, for loops, while and until structures, break, continue, and select statements. Also, explore file descriptors, array variables, variable scope, special parameters, and functions.
Fun with Control Structures in Shell Scripting
E N D
Presentation Transcript
Chapter 10:BASH Shell Scripting Fun with fi
In this chapter … • Control structures • File descriptors • Variables
Control structure tests • Control structures depend on a test that equates either true or false • The test builtin in bash allows logical, relational, and file property-based tests • Syntax: test expression OR [ expression ]
test expressions • If expression is true, test returns 0; if false, it returns not 0 (usually 1) • Comparing text strings string1 = string2 string1 != string2 • Comparing numbers num1 –OP num2 • Where OP can be eq, ne, lt, gt, le, ge
test expressions con’t • File tests -optionfilename where option can be: d : file is a directory y : file exists f : file is a regular file Plus many more (check man bash)
Other test-commands • Instead of test and [ ] you can use other bash contructs • ((expression)) can be used for integer comparisons • [[expression]] can be used for logical expressions and string comparisons • See pages 505-506 for complete list
if … then structure • Syntax: if test-command then commands fi • test-command must evaluate true or false • commands can be zero or more lines
if … then … else structure • Syntax: if test-command then commands else commands fi • Same guidelines as if…then
if … then … elif structure • Syntax: if test-command then commands elif test-command then commands … else commands fi
if … then … elif con’t • You can have one or more elif blocks • Remember, each elif line is following by a then statement • Rather than multiple elif’s, might try a case statement instead
case structure • Syntax: case test-string in pattern-1) commands ;; pattern-2) commands ;; … esac
case structure con’t • test-string is any string – usually we want to check the contents of a variable, so we’d use something like $myvar • The patterns are similar to ambiguous file references – so the shell special characters apply ([ ], ?, *, |) • If the last pattern is *, it’s a catch all or default
for … in structure • Syntax: for loop-index in argument-list do commands done • loop-index is a variable name – does not have to be previously declared • argument-list is a space-delimited list
for structure • Syntax: for loop-index do commands done • Similar to for … in except values of loop-index are populated with the script’s command line arguments
while structure • Syntax: while test-command do commands done • commands will continue to be run until test-command becomes false
until structure • Syntax: until test-command do commands done • commands will continue to be run until test-command becomes true
break and continue • break exits a loop structure – jumps down to after done statement • continue exits current loop iteration – jumps down to the done statement, and begins next loop iteration test • Used to short circuit loops
select structure • Syntax: select varname [in arg1 arg2 …] do commands done • Similarly to a for loop, varname need not be declared prior • If in args omitted, command line arguments used
select structure con’t • select structure displays a numbered menu allowing user to select an arg • After displaying the menu, select displays the PS3 prompt – by default it’s #? • Set PS3 to customize the prompt to something more intelligible • The user’s selection (what was actually typed) is stored in REPLY
File descriptors • Recall 0<, 1>, 2> … now let’s make more • Syntax: exec n> outfile AND exec m< infile • exec associates streams with files • Then can treat those streams just like the standard ones • To close: exec n>&- AND exec m<&-
Array Variables • Recall we declare bash variables with the format varname=value • To declare an array, use:arrayname=(elements …) • Array is zero based and referenced via [ ] • [*] returns all the elements in the array, IFS delimited • [@] returns all the elements in the array, for the purpose of copying entire arrays
Variable Scope • By default, bash variables have local scope • To make global, you must use export (or declare/typeset with –x) • Variables used in a shell script are local to the script, unless exported
Special Parameters • $$ -- the PID of the process running • $? -- the exit status of the last process • $# -- the number of command line arguments • $0 -- the name of the calling program • $n -- the nth command line argument • ${n} must be used for n > 9 • the shift builtin rotates through the arguments
Null and unset variables • ${varname:-default} : if varname is not set or is null, substitutes for default • ${varname:=default} : if varname is not set or null, substitues for default and sets varname • ${varname:?message} : if varname is not set, displays an error
Functions • Syntax:function name () {…} • Note on scope – functions have same scope as calling script/shell … which means you can access (or step on!) existing variables
Here document • Allows you to do standard input redirection within a script • Denoted by << followed by a sentinel • Ex: sort <<MyList dog cat bird MyList
type • Provides info about a command/builtin • Syntax: type command • Basically, what is being run? • Path to executable • Shell builtin • Shell alias • Hashed reference
read • Syntax: read [options] [varname] • Reads input from standard in • If varname not supplied, input goes in REPLY • Gets everything the user types in before hitting RETURN
read con’t • Options • a array – sticks each word into an element of array • d delimiter – use a delimiter other than NEWLINE • n num – read n characters • p prompt – displays prompt to user • u number – grabs from given file descriptor
getopts • Easy way to make your script use classic option syntax • Syntax: getopts optstring varname [args …] • optstring is a list of options (characters) • Options followed by : denote required args • If optstring starts with : getopts handles errors • varname used to hold each argument
getopts con’t • Usually placed in a loop to read options in one at a time for processing • Keyword variable OPTIND contains an index of what option you’re processing • Keyword variable OPTARG contains the argument for the given option
getopts con’t • Ex: while getopts :ab:c myvar do case $arg in a) do stuff ;; b) do other stuff, with arg ;; c) do something ;; :) display error for missing arg ;; \?) display error for wrong opt ;; esac done
Misc • More builtins • Arithmetic/Logical Evaluation • Operators • Recursion