BASH Scripting Intro and Variables.

Slides:



Advertisements
Similar presentations
CIS 240 Introduction to UNIX Instructor: Sue Sampson.
Advertisements

CS Lecture 03 Outline Sed and awk from previous lecture Writing simple bash script Assignment 1 discussion 1CS 311 Operating SystemsLecture 03.
Introducing the Command Line CMSC 121 Introduction to UNIX Much of the material in these slides was taken from Dan Hood’s CMSC 121 Lecture Notes.
Linux+ Guide to Linux Certification, Second Edition
Shell Basics CS465 - Unix. Shell Basics Shells provide: –Command interpretation –Multiple commands on a single line –Expansion of wildcard filenames –Redirection.
Now, return to the Unix Unix shells: Subshells--- Variable---1. Local 2. Environmental.
Information Networking Security and Assurance Lab National Chung Cheng University 1 What Linux is? Free Unix Like Open Source Network operating system.
CS 497C – Introduction to UNIX Lecture 34: - Shell Programming Chin-Chih Chang
More Shell Basics CS465 - Unix. Unix shells User’s default shell - specified in /etc/passwd file To show which shell you are currently using: $ echo $SHELL.
Guide To UNIX Using Linux Third Edition
Shell Script Examples.
7/17/2009 rwjBROOKDALE COMMUNITY COLLEGE1 Unix Comp-145 C HAPTER 2.
CTEC 1863 – Operating Systems Shell Scripting. CTEC F2 Overview How shell works Command line parameters –Shift command Variables –Including.
Advanced Shell Programming. 2 Objectives Use techniques to ensure a script is employing the correct shell Set the default shell Configure Bash login and.
Lesson 7-Creating and Changing Directories. Overview Using directories to create order. Managing files in directories. Using pathnames to manage files.
Writing Shell Scripts ─ part 1 CSE 2031 Fall September 2015.
Chapter Nine Advanced Shell Scripting1 System Programming Advanced Shell Scripting.
8 Shell Programming Mauro Jaskelioff. Introduction Environment variables –How to use and assign them –Your PATH variable Introduction to shell programming.
Week 7 Working with the BASH Shell. Objectives  Redirect the input and output of a command  Identify and manipulate common shell environment variables.
Agenda User Profile File (.profile) –Keyword Shell Variables Linux (Unix) filters –Purpose –Commands: grep, sort, awk cut, tr, wc, spell.
Chapter 5 Bourne Shells Scripts By C. Shing ITEC Dept Radford University.
– Introduction to the Shell 10/1/2015 Introduction to the Shell – Session Introduction to the Shell – Session 2 · Permissions · Users.
An Introduction to Unix Shell Scripting
The UNIX Shell. The Shell Program that constantly runs at terminal after a user has logged in. Prompts the user and waits for user input. Interprets command.
Shells. A program that is an interface between a user at a terminal and the computers resouces ▫The terminal may be real or an emulator The shell is.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Shell Script Programming. 2 Using UNIX Shell Scripts Unlike high-level language programs, shell scripts do not have to be converted into machine language.
Introduction to Linux OS (IV) AUBG ICoSCIS Team Prof. Volin Karagiozov March, 09 – 10, 2013 SWU, Blagoevgrad.
Introduction to Bash Programming Ellen Zhang. Previous three classes What have we learnt so far ?
Linux+ Guide to Linux Certification, Third Edition
Linux Operations and Administration
Basic Shell Scripting - Part 1 Objective - Learn to: Read Start-up Files Edit Start-up Files Modify Your User Environment Communicate with Users Write.
UNIX Shell Script (1) Dr. Tran, Van Hoai Faculty of Computer Science and Engineering HCMC Uni. of Technology
CS465 - UNIX The Bourne Shell.
UNIX Commands. Why UNIX Commands Are Noninteractive Command may take input from the output of another command (filters). May be scheduled to run at specific.
Workbook 6 – Part 2 The Bash Shell
Linux+ Guide to Linux Certification Chapter Eight Working with the BASH Shell.
Unix/Linux cs3353. The Shell The shell is a program that acts as the interface between the user and the kernel. –The shell is fully programmable and will.
5 1 Data Files CGI/Perl Programming By Diane Zak.
©Colin Jamison 2004 Shell scripting in Linux Colin Jamison.
Introduction to Programming Using C An Introduction to Operating Systems.
1 © 2000 John Urrutia. All rights reserved. Session 5 The Bourne Shell.
Using Linux Commands Lab 4. Using the Shell in Linux Commands Syntax  Options: could be added to the commands to change their behavior (-a, -la, --help)
Lesson 3-Touring Utilities and System Features. Overview Employing fundamental utilities. Linux terminal sessions. Managing input and output. Using special.
Environment After log in into the system, a copy of the shell is given to the user Shell maintains an environment which is distinct from one user to another.
Agenda Positional Parameters / Continued... Command Substitution Bourne Shell / Bash Shell / Korn Shell Mathematical Expressions Bourne Shell / Bash Shell.
CSCI 330 UNIX and Network Programming Unit III Shell, Part 1.
Agenda The Bourne Shell – Part II Special Characters Ambiguous File Reference Variable Names and Values User Created Variables Read-only Variables (Positional.
Linux+ Guide to Linux Certification, Second Edition
© Prepared By: Razif Razali 1 TMK 265: UNIX SYSTEM CHAPTER FOUR – QUOTING IN DETAIL.
Lesson 6-Using Utilities to Accomplish Complex Tasks.
Agenda The Bourne Shell – Part I Redirection ( >, >>,
Lesson 8-Specifying Instructions to the Shell. Overview An overview of shell. Execution of commands in a shell. Shell command-line expansion. Customizing.
1 Lecture 7 Introduction to Shell Scripts COP 3353 Introduction to UNIX.
Linux Tutorial Lesson Two *Getting Help in Linux *Data movement and manipulation *Relative and Absolute path *Processes Note: see chapter 1,2,3 from Linux.
Linux Administration Working with the BASH Shell.
Agenda Customizing a Unix/Linux account Environment Introduction to Start-up Files (.bash_profile,.bashrc,.profile,.kshrc) Safe Methods for Changing Start-up.
Shell scripts – part 1 Cs 302. Shell scripts  What is Shell Script? “Shell Script is series of command written in plain text file. “  Why to Write Shell.
ULI101 Week 10. Lesson Overview ● Shell Start-up and Configuration Files ● Shell History ● Alias Statement ● Shell Variables ● Introduction to Shell Scripting.
Introduction to Shells
Shell Features CSCI N321 – System and Network Administration
Prepared by: Eng. Maryam Adel Abdel-Hady
Bash Introduction (adapted from chapters 1 and 2 of bash Cookbook by Albing, Vossing, & Newham) CPTE 440 John Beckett.
CAP652 Lecture - Shell Programming
Shell Script Assignment 1.
Shell Environments.
Using Linux Commands Lab 3.
Linux Shell Script Programming
Chapter 3 The UNIX Shells
Introduction to Bash Programming, part 3
Presentation transcript:

BASH Scripting Intro and Variables

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

Overview Executing Variables I/O 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 chmodsfile requires path PATH+=:dir . sfile source sfile bash sfile sh sfile ./sfile sfile

Executing a Script Path set3 command chmod1 separate shell2 . script No source script bash script Yes sh script ./script script 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 Parameters are sent by entering values when the shell is called. Variable Result $0 name of called script $1 $2 … $9 parameter 1, 2,… 9 $# number of parameters $@ values of all parameters using: “1” “2”, etc (multiple parameters) $* “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 Result $0 params $1 $2 a b $# 3 $@ a b c $? $* $$ 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 assignment 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 echo ${myvar-`date`} clear variable myvar= shows a blank line delete variable unset myvar shows current date (myvar no longer exists) 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 initialized if var is not set, sets var to the word val + 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 Result val=Ron val2=Sue val:=$val2 Ron val:+$val2 Sue val:?$val2 val= val2=Sue i.e. val has no value val:=val2 val:+val2 val:?val2 variablesub: line 22: val: Sue val2=Sue i.e. val never set

Variable pattern matching # and % 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 ParentScript: ChildScript: Script Command Result name1=Ron name2=Sue export name2 sh ChildScript echo $name2 ChildScript: echo $name1 echo $name2 name2=Bob Script Command Result Reason ChildScript echo $name1 blank name1 is local to ParentScript and not exported echo $name2 Sue name2 is defined and exported from ParentScript ParentScript name2 cannot be transferred to ParentScript from ChildScript so ParentScript’s name2 is unchanged

readonly Variables declaring a value readonly makes it a constant, for example: name=Ron readonly name echo $name name=Sue 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) Description HOME home directory IFS Internal field separator PATH Directories to search for commands and scripts CDPATH Directories to use with the cd command PS1 Prompt to be used PS2 Prompt to be used if the command is continued on multiple lines PS3 Prompt string for select statements

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

PS1, PS2 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: PS1=‘\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 file. Search in your home directory for the .bash_profile file using: ls –a .bash_profile If it does not exist, copy the /etc/profile file 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] var1[ var2…] 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 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 \r\n 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 file

BASH Scripting Intro and Variables