Shell Programming. 222 Lecture Overview Shell variables Shell scripts Control flow and Boolean...
-
Author
myron-alexander -
Category
Documents
-
view
239 -
download
4
Embed Size (px)
Transcript of Shell Programming. 222 Lecture Overview Shell variables Shell scripts Control flow and Boolean...
-
Shell Programming
***
Lecture OverviewShell variablesShell scriptsControl flow and Boolean operatorsShell programming tipsShell programming examples
***
Shell VariablesUnlike simpler operating systems (such as DOS), UNIX shells provide powerful programming languagesEach shell has a different languageWe will only learn C Shell programming:A powerful programming languageIts syntax is similar to that of the C language
***
Shell VariablesLike in any programming language, the most basic elements are variablesC Shell variables are always of type stringHowever, they can be treated as numbers, and can be used for arithmetic operationsArrays of variables are also supported
***
Defining VariablesSince variables have no type, there is no need for a variable declarationTo define a variable, we simply assign some value to itAssigning values to variables is done using the set command:set [variable [= value]] ...
***
Defining VariablesWhen set is used without any arguments, the values of all variables currently defined in the shell are printedWhen set is used with a name but no value, the variable is created, but assigned an empty valueSuch variables can be used as Booleans
***
Using VariablesTo reference a variable in any shell command, the '$' sign is usedset name = Johnecho $nameJohn echo $shell/bin/tcshecho $namename: Undefined variable.
***
Un-defining VariablesWhen a variable is no longer needed, it can be freed using the unset command:
This can also be used for setting the value of a Boolean variable to falseunset variable set nameunset nameecho $namename: Undefined variable.
***
Arrays of VariablesTo define an array, a value must be assigned to each of its elementsThe list of values is enclosed within parentheses '(' and ')'Specific values can be accessed using square braces '[' and ']'
***
Arrays of VariablesUnlike C and Java, arrays in the C Shell are 1-based, not 0-basedIf array a has 3 elements, then they can be accessed as: a[1], a[2], a[3]To append a new element to an existing array, use the following:set a = ($a new_element)
***
Arrays of Variables Examplesset colors = (red green blue)echo $colorsred green blue echo $colors[2]greenecho $colors[2-3]green blueset colors = ($colors yellow)echo $colors[4]yellow set shapes = ("" "" "" "")set shapes[4] = squareecho $shapes[4]square
***
Numeric Variablesthe set command can only assign literal values to variablesTo allow the right-hand-sign of an assignment to be a logical or arithmetic expression, we use the '@' command:
Note: the space after the '@' is [email protected] [variable = expression] ...
***
ExpressionsAn expression can contain most of the operators available in C (or in Java):Arithmetic operators+, -, *, /, %Relational and logical operators>, =, 5)echo $result1 @ count += 5echo $count12 @ count++echo $count13
***
Numeric Variable TypeNumeric variables in the C Shell are always assumed to be integers trying to assign fractional values will fail:@ c = [email protected]: Badly formed number.echo $cc: Undefined variable.
***
Arrays of Numeric VariablesIn order to define an array of numeric values, the set command must be usedAfter the array is initialized, individual values can be changed using set, or using '@' and an expressionArrays can also be mixed, containing both numeric and string values
***
Arrays of Numeric Variables Exampleset ages = (0 0 0 0)@ ages[2] = [email protected] ages[3] = ($ages[2] + 4)echo $ages[3]19echo $ages0 15 19 0set ages[1] = teenecho $agesteen 15 19 0
***
Special Forms of VariablesNumber of elements in an array:
Number of characters in a regular variable:
Determine whether a variable is defined or not (1 if defined, 0 otherwise):$?variable$#array$%variable
***
Special Forms of Variables Example0
fri15
unset countryecho $?countryecho $days[$#days]echo $?countryset days = (mon tues wed thurs fri)echo $#days6
set country = "Israel"echo $%country
***
Variable ModifiersThe following modifiers can be appended to a variable, to extract only part of it
ModifierAction:rReturns the variable's root (until last '.'):eReturns the variable's extension:hReturns the variable's head (path):tReturns the variable's tail (file name)
***
Variable Modifiers Examplesset phones_path = ~demo/text/phones.txtecho $phones_path/home/demo/text/phones.txtecho $phones_path:etxtecho $phones_path:r/home/demo/text/phonesecho $phones_path:h/home/demo/textecho $phones_path:tphones.txtecho $phones_path:t:rphones
***
Quoting Shell VariablesAs we have seen, double quotes (") can be used to quote some special charactersHowever, this does not suppress variable substitution:set my_text = ~demo/textecho "The file is in the $my_text directory."The file is in the /home/demo/text directory.
***
Quoting Shell VariablesTo prevent variable substitution, the text should be enclosed in single quotes ('):
It is also possible to run a command, and store its output in a variable this is called command substitutionecho 'Store your name in the $user_name variable.'Store your name in the $user_name variable.
***
Command SubstitutionTo use command substitution, the command, along with its arguments, should be enclosed in backquotes (`):set satoshi_phone = `grep Satoshi phones.txt`echo $satoshi_phoneNAKAMURA, Satoshi 6453set name = Satoshiecho $name\'s phone number is: \`grep $name phones.txt | cut -d" " -f3`Satoshi's phone number is: 6453
***
Pre-defined Shell VariablesWhenever a shell is started, several variables are already definedThe values of some of these variables are constantly updated by the shellThe user can change the values of pre-defined variables to modify the behavior of the shell
***
Pre-defined Shell VariablesSome pre-defined variables have values, others only act as switches (Boolean)Shell variables that act as switches:$noclobber if set, does not allow the user to accidentally overwrite an existing file$ignoreeof when set, prevents accidental log-out using Ctrl-D. To leave a shell, exit or logout must be used
***
Pre-defined Shell VariablesShell variables that hold a value:$user contains the name of the current user$home contains the path to the home directory of the current user$path contains the command search path$shell contains the path to the current shell being usedMany more variables exist
***
Lecture OverviewShell variablesShell scriptsControl flow and Boolean operatorsShell programming tipsShell programming examples
***
Shell ScriptsA shell script is a file that contains commands to be executed by the shellAny command entered in response to a shell prompt can also be used in a scriptAdditionally, the shell provides control flow commands, designed specifically for use within shell scripts
***
Executing a Shell ScriptThere are two approaches to running a shell script:Running the script within the current shellMore efficient no shell start-up requiredVariable definitions remain in effect when the script ends, and can be used in the current sessionRunning the script in a newly-created shellSimilar to executing a binary program
***
Executing a Shell Scriptin the Current ShellBy using the source command, a script file can be executed in the current shell:
The script is assumed to be written in the language of the current shellIf the script was written in the language of a different shell an error may occursource script_file
***
Executing a Shell Script in a New ShellNormally, when a script is run, a new shell is created for running itThis can be done explicitly:
This is not very convenient, and still requires the user to know which shell should be used to interpret the script/bin/tcsh script_file
***
Executing a Shell Script in a New ShellThe name of the shell that should be used can be embedded in the script itselfSet the first line of the script to:
If this approach is used, the script file must be made executable:#!/bin/tcshchmod +x script_file
***
Automatically Executed Shell ScriptsSeveral scripts are automatically executed by the C Shell at different times:.login runs at the beginning of a session.logout runs at the end of a session.tcshrc or .cshrc runs every time a new shell is createdAll of these files must be located in the user's home directory
***
The .tcshrc FileThe .tcshrc (or .cshrc) file is run once when the user logs in, and again every time a new shell is created (for example when a shell script file is executed)It is normally used for defining local variables and common aliasesAny C Shell command can be used in it
***
A Sample .tcshrc File#!/bin/tcsh
# Define aliases.alias l ls -F --coloralias ll l -lalias la ll -aalias hgrep 'h | grep'alias + more
set noclobberset ignoreeofset nobeep
umask 077
***
Command Line Arguments $argv The '$argv' variable contains the command line arguments:'$argv[0]' the name of the current script'$argv[1]', '$argv[2]', specific command line arguments'$argv[*]' all command line arguments'$#argv' the number of command line arguments
***
Special Variables for Use WithinShell ScriptsThe following shortcuts may be used:'$*' instead of '$argv[*]''$1' instead of '$argv[1]', '$2' instead of '$argv[2]', etc.'$#' instead of '$#argv''$