BASH Scripting Intro and Variables Objectives Introduce Unix

BASH Scripting Intro and Variables

Objectives • Introduce Unix script writing including: – introducing variables – locality – basic I/O • Introduce script execution • Introduce the. bash_profile

Overview • Executing • Variables – – – – creating/assignment accessing list variables (arrays) exporting read only eliminating predefined • I/O – read – echo (write)

Example of First Script -bash-3. 2$cat helloworld # show contents of script echo Hello World!! # display Hello World!! on screen -bash-3. 2$. helloworld # execute script (note the period space (. ) prior to the script name) Hello World!!

Steps for scripts vi sfile requires execute permission sfile chmod sfile requires path PATH+ =: dir . sfile source sfile bash sfile . /sfile

Executing a Script command. script source script chmod 1 No No separate shell 2 No No bash script. /script No No Yes Yes Yes Path No No No Yes set 3 No No 1 – requires execute mode 2 – runs in separate shell. Variables set have no affect outside of script even with export but exported variables are exported to sub scripts 3 – requires PATH variable to be set to point to current directory (. )

Shell Positional Parameters are sent by entering values when the shell is called. Variable $0 $1 $2 … $9 $# $@ $* $? $$ Result name of called script parameter 1, 2, … 9 number of parameters values of all parameters using: “ 1” “ 2”, etc (multiple parameters) values of all parameters using: “ 1 2 etc” (a single parameter) return code Process ID (PID)

Shell Positional Parameters Assuming a script called params was called using the parameters a b c: params a b c Variable $0 $1 $2 $# $@ $? $* $$ Result params ab 3 abc 0 abc 13061

set • Parameters may be set within a script using the set command – Example: set w x y z will set parameters 1 through 4 to “w” “x” “y” and “z”, even if they were set to values when the shell was called. If fewer variables were set than were called the “extra” variables are lost – Example: if a script called paramsset is called using: paramsset a b c d and inside paramsset is the command: set x y z x, y, and z are the only values available (“d” is lost)

Variables • creating – must begin with a character (a-z, A-Z) – may contain alphanumeric characters (a-z, A-Z, 0 -9) and the underscore character(_) – case sensitive, thus Ron is different than ron • assignment – var=val NOTE: no spaces surrounding = – var=“space delimited vals”

Viewing Variables Set • Show all variables set: set

Variables • accessing – $var - shows value of variable – ${var}othertext – ensures that var is the substitution variable (not varothertext) – ${var-val} - shows value of var if defined otherwise uses val (if val includes spaces, it must be enclosed in “; if val is a command must be inclosed in `)

Variable Examples Description Command create a variable using a value or the output from a command myvar=“Fri Oct 19 11: 31: 16 EDT 2007” or myvar=`date` shows variable echo $myvar shows variable echo ${myvar-`date`} clear variable myvar= shows a blank line echo ${myvar-`date`} delete variable unset myvar shows current date (myvar no longer exists) echo ${myvar-`date`} Please note the ` is called a grave accent and is NOT a single quote. It is located above the tab key, on the same key as the tilde ~. Do not confuse this with the single quote (next to the Enter key).

More Variable Substitution • ${var: opval} op Purpose Description = Initializing var to val if it is not if var is not set, sets var to the word val initialized + Test for existence of a variable If var exists and is not null, return val else return null ? Catching and terminating scripts with undefined or unitialized variables if var has been set return its value, else val message displayed script terminates

Variable substitution examples Variables set Substitution val: =$val 2 val=Ron val 2=Sue val: +$val 2 val: ? $val 2 val: =val 2 val= val 2=Sue val: +val 2 i. e. val has no value val: ? val 2=Sue i. e. val never set val: =val 2 val: +val 2 val: ? val 2 Result Ron Sue Sue variablesub: line 22: val: Sue

Variable pattern matching # and % ${variable#pattern} If the pattern matches the beginning of the variable's value, delete the shortest part that matches and return the rest. ${variable##pattern} If the pattern matches the beginning of the variable's value, delete the longest part that matches and return the rest. ${variable%pattern} If the pattern matches the end of the variable's value, delete the shortest part that matches and return the rest. ${variable%%pattern} If the pattern matches the end of the variable's value, delete the longest part that matches and return the rest.

Variable pattern matching # and % • Pattern-matching operators are useful for stripping off components of pathnames, such as directory prefixes and filename suffixes. • An easy way to remember the usage is to think of how we write percents. For example 75% the number (#) 75 precedes and the percent sign (%) follows • Doubling the symbol (## or %% indicates repeated deletions until pattern is found.

# and % Examples An example that shows how all of the operators may be used. Assume that the variable path has the value: /home/student/project/Class. Name. java Expression Result Comments $path /home/student/project/Class. Name. java ${path##/*/} Class. Name. java deletes all directories until file dot (. ) is found ${path#/*/} student/project/Class. Name. java deletes first directory only ${path%%. *} /home/student/project/Class deletes all dot (. ) filenames from right ${path%. *} /home/student/project/Class. Name deletes first occurrence from right

Variables • Exporting: Variables are considered “local” to the script, that is, a variable used in a particular script has no affect outside of that particular script. The export command will allow the variable to be used in a child script. A child script is a script that has been started from another script (the parent). It is important to note that exporting only goes from parent to child not from child to parent.

Variable exporting Parent. Script: name 1=Ron name 2=Sue export name 2 sh Child. Script echo $name 2 Result Child. Script: echo $name 1 echo $name 2=Bob Script Command Child. Script echo $name 1 blank name 1 is local to Parent. Script and not exported Child. Script echo $name 2 Sue name 2 is defined and exported from Parent. Script echo $name 2 Sue Reason name 2 cannot be transferred to Parent. Script from Child. Script so Parent. Script’s name 2 is unchanged

readonly Variables • declaring a value readonly makes it a constant, for example: name=Ron readonly name echo $name=Sue echo $name results in the following error: readonly: line 4: name: readonly variable

eliminating Variables – var= simply removes the value (sets it to null) of the variable NOT the variable itself – unset var removes the variable altogether

predefined Variables (selected) Variable Description HOME home directory IFS Internal field separator PATH Directories to search for commands and scripts CDPATH Directories to use with the cd command PS 1 Prompt to be used PS 2 Prompt to be used if the command is continued on multiple lines PS 3 Prompt string for select statements

predefined Variables (selected) Variable Description MAIL file that receives your mail MAILCHECK Interval used by the shell to check for mail (default 600 sec) SHELL TERM TZ

PS 1, PS 2 variables (selected*) Value Description a ASCII bell (the beep) A, t, T Current Time in HH: MM (24 hours), HH: MM: SS (24 and 12 hours) D{format} Date in format (see http: //linux. die. net/man/3/strftime) h, H hostname, complete hostname s Name of shell u Username v Version w Current directory Example: PS 1=‘s-v$’ shows -bash-3. 2$, which is the current default. *For a complete list of variables, see pages 365 -366 in Unix in a Nutshell

I/O • read : allow the user to enter data into a variable from standard input (keyboard) • echo : displays contents onto standard output (display)

. bash_profile • A user may have a hidden file called. bash_profile • This file is really a script that is automatically called when one logs in to the machine. • . bash_profile is responsible for setting up the Unix environment specifically for you. The Windows/DOS equivalents for this was autoexec. bat and config. sys • A key variable in the. bash_profile is the PATH variable. This variable provides Unix with a search path for locating files

What to do if you don’t have a. bash_profile. • Search in your home directory for the. bash_profile using: ls –a. bash_profile • If it does not exist, copy the /etc/profile to your home directory renaming it. bash_profile This file is extremely important, so be sure to save a copy of it, prior to altering it, in order to restore it, should things go wrong.

Modifying the PATH variable • To modify the PATH variable to add a directory to the existing PATH use the following commands: PATH+=“: newpath” • In Unix the colon (: ) is a separator between different paths. In Windows/DOS the separator is a semi-colon (; ). Be extremely careful in modifying the PATH, as many commands will no longer work if the PATH is corrupted.
![I/O (read) • format: read [options] var 1[ var 2…] • Options (selected) – I/O (read) • format: read [options] var 1[ var 2…] • Options (selected) –](http://slidetodoc.com/presentation_image_h2/c03ec8a9706c278f0c58fa51d96bdfca/image-30.jpg)
I/O (read) • format: read [options] var 1[ var 2…] • Options (selected) – -p ‘string’ : prompt with a string (no need to use an echo for prompting) – -s : hide input, good for password entries – -t seconds : Wait for input specified number of seconds, if time expires do not set variables
![I/O (echo) • format: echo [options] [strings] • Options: – -e : Enable escape I/O (echo) • format: echo [options] [strings] • Options: – -e : Enable escape](http://slidetodoc.com/presentation_image_h2/c03ec8a9706c278f0c58fa51d96bdfca/image-31.jpg)
I/O (echo) • format: echo [options] [strings] • Options: – -e : Enable escape character interpretation (see next slide) – -n : Do not append a newline to the output (useful for concatenating strings or when prompting for a read and read to take place on same line as prompt – -E : disable interpretation of escape characters

Prompt and Read Examples -bash-3. 2$cat helloworld #read name from keyboard read -p 'Enter name: ' name # print out hello world echo Hello $name!! -bash-3. 2$. helloworld Enter name: Sue Hello Sue!! -bash-3. 2$cat helloworld #prompt for name echo Enter Name: #read name from keyboard read name # print out hello world echo Hello $name!! -bash-3. 2$. helloworld Enter Name: Soumyaroop Hello Soumyaroop!!

Escape Characters • the escape character, a backslash (), allows a different interpretation for the following selected characters: – a : Audible alert – b : backspace – c : continue on same line (same as –n option) – e : escape character – f : form feed – n : newline – r : carriage return (on some systems rn are both required for a new line) – t : horizontal tab

Review • Introduced Unix script writing including: – introducing variables – locality – basic I/O • Introduced script execution • Introduced the. bash_profile

BASH Scripting Intro and Variables
- Slides: 35