Shell Scripting – Putting it All Together
Agenda Escaping Characters Wildcards Redirecting Output Chaining and Conditional Chaining Unnamed and Named Replacement Parameters IF statement IF ELSE statement Menus Subroutines and Procedures
Escaping Characters The “&” and “|” are special characters to the command interpreter If 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 Symbol Input & Output By using the ^ symbol the Shell does not interpret the & symbol as a chaining command and thus displays the & as a string
Wildcards Most commands allow you to use wildcard characters to handle more than one file at a time. Asterisk (*) – substitutes multiple characters Question Mark (?) – substitutes only 1 character
Wildcards Example BUDGET.JANBUDGET.FEBBUDGET.MAR BANK.DOCREPORT12.DOCREPORT2.DOC C:\>dir *.* C:\>dir budget.* C:\>dir b* C:\>dir *.doc C:\>dir budget.?a? C:\>dir report?.doc
Redirecting Output You can modify where the output of a command goes By default the output of a commands is generally displayed on the screen You 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
Examples File1.txt This is file 1. File2.txt This is file 2. C:\>type file1.txt >> file2.txt C:\>type file1.txt > file2.txt C:\>type file1.txt > file3.txt
Connecting Commands with a Pipe You 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 | more C:\>dir | sort
Chaining and Conditional Chaining & - chains two commands together ECHO Unsuccessful & GOTO :EOF && - executes the second command ONLY if the first command was successful COPY *.txt && ECHO Operation Successful || - executes the second command ONLY if the first command was unsuccessful COPY *.txt || ECHO Operation Unsuccessful
Replaceable Parameters A 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, %9 Named 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 Entrapment Good programming tests for the existence of parameters and displays a message Documentation and messages Good programming provides the user with correct command syntax
Error Entrapment and Documentation
Named Replacement Parameters System-wide variables used to store information Two 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
GOTO command Use 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 Command On 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 Tests IF [NOT]“string1” == “string2” [command] compares two strings for same value IF [NOT] ERRORLEVEL 1 [command] Commands return all values 1 AND above 0 Success 1 Failure 2 execution failure4 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 directory To check a directory, add “\.” after the directory name IF [NOT] DEFINED [variable] [command] Tests for the existence of a variable
IF and GOTO Example
IF ELSE
Menu Displaying choices to the user and controlling user selection Branch using a user defined variable Using IF or IF /I to compare strings Branch using ERRORLEVEL Trap the actual key on the keyboard
Branching – Using variable
Branching – Using Error Level based on ASCII valuesASCII
Subroutines and Procedures Normally 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 command The GOTO command creates an unconditional branch to a label A label identifies a location in your script A label is preceded with a colon, ie. :Start The Shell then executes the commands after the label
Procedures Are created using the CALL command External Internal 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 Procedures MyScript.cmd :start cmd1 CALL :Copy :Copy cmd1 cmd2 :Make cmd1 :EOF 1 2 GOTO :EOF