shell scripting – putting it all together. agenda escaping characters wildcards redirecting output...
TRANSCRIPT
Shell Scripting – Putting it All Together
AgendaEscaping CharactersWildcardsRedirecting OutputChaining and Conditional ChainingUnnamed and Named Replacement ParametersIF statementIF ELSE statementMenusSubroutines and Procedures
Escaping CharactersThe “&” and “|” are special characters to the
command interpreterIf you wish to use these characters in a text
string, they must be “escaped” by using the “^” (caret symbol)
For example you want to echo the phrase “Yes & No”
Caret SymbolInput & Output
By using the ^ symbol the Shell does not interpret the & symbol as a chaining command and thus displays the & as a string
WildcardsMost commands allow you to use wildcard
characters to handle more than one file at a time.
Asterisk (*) – substitutes multiple charactersQuestion Mark (?) – substitutes only 1
character
Wildcards ExampleBUDGET.JAN BUDGET.FEB
BUDGET.MARBANK.DOC REPORT12.DOC
REPORT2.DOC
C:\>dir *.*C:\>dir budget.*C:\>dir b*C:\>dir *.docC:\>dir budget.?a?C:\>dir report?.doc
Redirecting OutputYou can modify where the output of a
command goesBy default the output of a commands is
generally displayed on the screenYou can redirect the output to a file (>, >>)You can redirect the output to be used as
input for another command (|)
Redirecting Output to a File> - when you redirect output to an existing
file, the redirected output replaces the original file
>> - you can add, or append to the end of an existing file
If the file doesn’t exist, it will be created in either case
ExamplesFile1.txt
This is file 1.File2.txt
This is file 2.C:\>type file1.txt >> file2.txtC:\>type file1.txt > file2.txtC:\>type file1.txt > file3.txt
Connecting Commands with a PipeYou can redirect the output of one command
to be the input of another. The two commands become connected using a pipe (|). You pipe the output of one command and use it as the input for a filter command.
C:\>dir \DOS | moreC:\>dir | sort
Chaining and Conditional Chaining& - chains two commands together
ECHO Unsuccessful & GOTO :EOF&& - executes the second command ONLY if
the first command was successfulCOPY *.txt && ECHO Operation Successful
|| - executes the second command ONLY if the first command was unsuccessfulCOPY *.txt || ECHO Operation Unsuccessful
Replaceable ParametersA replaceable parameter is a “placeholder”
for information entered on the command line and inserted by the command interpreter into the script during run time
2 types:Unnamed Replacement Parameters
Use %1, %2, %3, %4, %5, %6, %7, %8, %9Named Replacement Parameters
Use a named variable, either e.g. %path% -- a predefined environment variable,
or SET [variable]=[value] -- user defined variable
Unnamed Replacement Parameters
• Names are “hardwired” in the script – no flexibility
• No user input before script runs – no dynamic changes
• Changes to script must be retyped – thus, error prone
Unnamed Replacement Parameters
• Statements are not “hardwired” – gives flexibility
• User input on the CLI – allows dynamic changes
• No retyping of code – thus, less error prone
Unnamed Replacement Parameters
Using Parameters Requires…
Error EntrapmentGood programming tests for the existence of
parameters and displays a messageDocumentation and messages
Good programming provides the user with correct command syntax
Error Entrapment and Documentation
Named Replacement ParametersSystem-wide variables used to store informationTwo types
Environment variables
Can only be added, deleted or modified by members of the administrators group
user defined
Can be added, deleted and modified by members of the users group
Environment Variables•The environment is an area of memory which the operating system uses as a scratch pad
•Stores “mission critical” information such as:
•COMPUTERNAME
•USERNAME
•USERPROFILE
•OS
•PATH
•TEMP and TMP + MANY MORE SEE SET
Predefined Environment Variables
User Defined Variables
•SET [variable]=[string]
used to create a variable
•SET /P [variable]=prompt[string]
•Used to capture user input
•SET /A [variable]=[value]
•Used to do arithmetic
•All information stored as text strings, even numbers
Named Replacement Parameters
Named Replacement Parameters
GOTO commandUse with caution if the label is before the
script, you can create an endless loop (unless there is a control to bypass the GOTO) for example
GOTO CommandOn the other hand, if the label is after the
GOTO statement, you can skip commands and jump to a new section
Execution of the script will continue to the end and you cannot go back to the unexecuted commands unless you use another GOTO
GOTO Command
Jumps to :Copy and executes the remaining commands
4 Types of Conditional TestsIF [NOT]“string1” == “string2” [command]
compares two strings for same valueIF [NOT] ERRORLEVEL 1 [command]
Commands return all values 1 AND above 0 Success 1 Failure2 execution failure 4 math failure
IF [NOT]“%ERRORLEVEL%” == “2” [command]Tests for a specific value ONLY
IF [NOT] EXIST filename [command]Checks to see if a file is located in that directoryTo check a directory, add “\.” after the directory name
IF [NOT] DEFINED [variable] [command]Tests for the existence of a variable
MenuDisplaying choices to the user and controlling
user selectionBranch using a user defined variable
Using IF or IF /I to compare stringsBranch using ERRORLEVEL
Trap the actual key on the keyboard
Branching – Using variable
Branching – Using Error Level• based on ASCII values
Subroutines and ProceduresNormally the “command interpreter”
executes scripts line by line starting at the beginning of a file
To change the order of execution we use subroutines and procedures
Using Subroutines and Procedures helps to organize your code for easier reading and creates “building blocks” of code which can be easily reused
Subroutines Are created with the GOTO commandThe GOTO command creates an
unconditional branch to a labelA label identifies a location in your script
A label is preceded with a colon, ie. :StartThe Shell then executes the commands after
the label
ProceduresAre created using the CALL command
ExternalInternal
The difference between a subroutine and a procedure is how the Shell behaves
With procedures execution continues at the designated label, proceeds to the end of the file and then returns to the line following the CALL statement
External Procedures
1
2
Internal ProceduresMyScript.cmd
:startcmd1CALL :Copy
:Copycmd1cmd2
:Makecmd1
:EOF
12
GOTO :EOF