Writing Scripts Hadi Otrok COEN 346.

Slides:



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

Introduction to Unix – CS 21 Lecture 11. Lecture Overview Shell Programming Variable Discussion Command line parameters Arithmetic Discussion Control.
Introduction to C Programming
More about Shells1-1 More about Shell  Shells (sh, csh, ksh) are m Command interpreters Process the commands you enter m High-level programming languages.
CS Lecture 03 Outline Sed and awk from previous lecture Writing simple bash script Assignment 1 discussion 1CS 311 Operating SystemsLecture 03.
Shell Programming Software Tools. Slide 2 Shells l A shell can be used in one of two ways: n A command interpreter, used interactively n A programming.
Guide To UNIX Using Linux Third Edition
Guide To UNIX Using Linux Third Edition
Introduction to Unix (CA263) Introduction to Shell Script Programming By Tariq Ibn Aziz.
Shell Programming 1. Understanding Unix shell programming language: A. It has features of high-level languages. B. Convenient to do the programming. C.
Bash Shell Scripting 10 Second Guide Common environment variables PATH - Sets the search path for any executable command. Similar to the PATH variable.
Shell Programming, or Scripting Shirley Moore CPS 5401 Fall August 29,
1.1 Command Substitution The backquote “`” is different from the single quote “´”. It is used for command substitution: `command`  $ LIST=`ls` $ echo.
Chapter Seven Advanced Shell Programming. 2 Lesson A Developing a Fully Featured Program.
Advanced Shell Programming. 2 Objectives Use techniques to ensure a script is employing the correct shell Set the default shell Configure Bash login and.
UNIX command line. In this module you will learn: What is the computer shell What is the command line interface (or Terminal) What is the filesystem tree.
Agenda Control Flow Statements Purpose test statement if / elif / else Statements for loops while vs. until statements case statement break vs. continue.
Introduction to Shell Script Programming
1 Operating Systems Lecture 3 Shell Scripts. 2 Shell Programming 1.Shell scripts must be marked as executable: chmod a+x myScript 2. Use # to start a.
1 Operating Systems Lecture 3 Shell Scripts. 2 Brief review of unix1.txt n Glob Construct (metacharacters) and other special characters F ?, *, [] F Ex.
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.
An Introduction to Unix Shell Scripting
Linux Shell Programming Tutorial 3 ENGR 3950U / CSCI 3020U Operating Systems Instructor: Dr. Kamran Sartipi.
Shell Scripting Todd Kelley CST8207 – Todd Kelley1.
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 Bash Programming Ellen Zhang. Previous three classes What have we learnt so far ?
Linux+ Guide to Linux Certification, Third Edition
Linux Operations and Administration
Shell Scripting AFNOG IX Rabat, Morocco May 2008.
#!/bin/sh echo Hello World cat Firstshellscript.sh Firstshellscript.sh.
Shell Programming. Introducing UNIX Shells  Shell is also a programming language and provides various features like variables, branching, looping and.
1 System Administration Introduction to Scripting, Perl Session 3 – Sat 10 Nov 2007 References:  chapter 1, The Unix Programming Environment, Kernighan.
Linux+ Guide to Linux Certification Chapter Eight Working with the BASH Shell.
CSC 352– Unix Programming, Spring 2015 March 2015 Shell Programming (Highlights only)
Shell Programming. Creating Shell Scripts: Some Basic Principles A script name is arbitrary. Choose names that make it easy to quickly identify file function.
Shell Programming Learning Objectives: 1. To understand the some basic utilities of UNIX File 2. To compare UNIX shell and popular shell 3. To learn the.
©Colin Jamison 2004 Shell scripting in Linux Colin Jamison.
Chapter Six Introduction to Shell Script Programming.
CSCI 330 UNIX and Network Programming Unit IX: Shell Scripts.
Executable scripts. So far We have made scripts echo hello #for example And called it hello.sh Run it as sh hello.sh This only works from current directory?
Agenda Positional Parameters / Continued... Command Substitution Bourne Shell / Bash Shell / Korn Shell Mathematical Expressions Bourne Shell / Bash Shell.
Shell script – part 2 CS 302. Special shell variable $0.. $9  Positional parameters or command line arguments  For example, a script myscript take 2.
Assigning Values 1. $ set One Two Three [Enter] $echo $1 $2 $3 [Enter] 2. $set `date` [Enter] $echo $1 $2 $3 [Enter] 3. $echo $1 $2 $3 $4 $5 $6 [Enter]
Shell Script Reference: Linux Shell Scripting Tutorial v1.05r3 A Beginner's handbook
1 Lecture 7 Introduction to Shell Scripts COP 3353 Introduction to UNIX.
Shell Scripting September 27, 2004 Class Meeting 6, Part II * Notes adapted by Lenwood Heath from previous work by other members of the CS faculty at Virginia.
 Prepared by: Eng. Maryam Adel Abdel-Hady
Linux Administration Working with the BASH Shell.
 Prepared by: Eng. Maryam Adel Abdel-Hady
Agenda Customizing a Unix/Linux account Environment Introduction to Start-up Files (.bash_profile,.bashrc,.profile,.kshrc) Safe Methods for Changing Start-up.
Lab 7 Shell Script Reference: Linux Shell Scripting Tutorial v1.05r3 A Beginner's handbook
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.
INTRODUCTION TO SHELL SCRIPTING By Byamukama Frank
1 Lecture 8 Shell Programming – Control Constructs COP 3353 Introduction to UNIX.
Bash Shell Scripting 10 Second Guide.
Department of Computer Engineering
Linux Shell Programming
Prepared by: Eng. Maryam Adel Abdel-Hady
Chapter 9 Shell Programming
Agenda Bash Shell Scripting – Part II Logic statements Loop statements
Chapter 14: Writing Shell Scripts
CAP652 Lecture - Shell Programming
Shell Scripting March 1st, 2004 Class Meeting 7.
Variables, Expressions, and IO
Agenda Control Flow Statements Purpose test statement
Linux Shell Script Programming
Introduction to Bash Programming, part 3
Bash Scripting CS 580U - Fall 2018.
Introduction to C Programming
Presentation transcript:

Writing Scripts Hadi Otrok COEN 346

Agenda Creating Scripts Environmental Variables Read Command and If Statement Example

Programming or Scripting ? bash is not only an excellent command line shell, but a scripting language in itself. Shell scripting allows us to use the shell's abilities and to automate a lot of tasks that would otherwise require a lot of commands. Difference between programming and scripting languages: Programming languages are generally a lot more powerful and a lot faster than scripting languages. Programming languages generally start from source code and are compiled into an executable. This executable is not easily ported into different operating systems. A scripting language also starts from source code, but is not compiled into an executable. Rather, an interpreter reads the instructions in the source file and executes each instruction. Interpreted programs are generally slower than compiled programs. The main advantage is that you can easily port the source file to any operating system. bash is a scripting language. Other examples of scripting languages are Perl, Lisp, and Tcl.

Writing a script Open a text editor; for example: $ vi & and type the following inside it: #!/bin/bash This is a special clue given to the shell indicating what program is used to interpret the script. In this case, it is /bin/bash. # My first script Comment (not read by the interpreter) echo “Hello World” The first line tells Linux to use the bash interpreter to run this script. We call it hello.sh. Then, make the script executable: $ chmod 700 hello.sh $ ls –l -rwx hello.sh

Writing a Script Usually, we type the following to run the script: $./hello.sh Now, the question is: How we can execute the script without typing./ When you type in the name of a command, the system does not search the entire computer to find where the program is located. That would take a long time. The shell maintains a list of directories where executable files (programs) are kept, and just searches the directories in that list. So, if we add our directory to the list of directories we can run our script as any command.

Writing a Script This list of directories is called your path. echo $PATH This will return a colon separated list of directories that will be searched if a specific path name is not given when a command is attempted. To execute the program without./ we have to do the following: By setting PATH=$PATH:. our working directory is included in the search path for commands, and we simply type: $ hello.sh

Variables We can use variables as in any programming languages. Their values are always stored as strings, but there are mathematical operators in the shell language that will convert variables to numbers for calculations. We have no need to declare a variable, just assigning a value to its reference will create it. Example #!/bin/bash STR=“Hello World!” echo $STR Line 2 creates a variable called STR and assigns the string "Hello World!" to it. Then the value of this variable is retrieved by putting the '$' in at the beginning.

Environmental Variables There are two types of variables: Local variables Environmental variables Environmental variables are set by the system and can usually be found by using the env command. Environmental variables hold special values. For instance, $ echo $SHELL /bin/bash $ echo $PATH /usr/X11R6/bin:/usr/local/bin:/bin:/usr/bin Environmental variables are defined in /etc/profile, /etc/profile.d/ and ~/.bash_profile. These files are the initialization files and they are read when bash shell is invoked. When a login shell exits, bash reads ~/.bash_logout

How to use the read command The read command allows you to prompt for input and store it in a variable. Example (read.sh) #!/bin/bash echo -n “Enter name of file to delete: ” read file echo “Type 'y' to remove it, 'n' to change your mind... ” rm -i $file echo "That was YOUR decision!" Line 3 creates a variable called file and assigns the input from keyboard to it. Then the value of this variable is retrieved by putting the '$' in at its beginning.

Read Options read –s (does not echo input) read –nN(accepts only N characters of input) read –p “message” (prompts message) read –tT(accepts input for T seconds) Example $ read –s –n1 -p “Yes (Y) or not (N)?” answer Yes (Y) or not (N) ? Y $ echo $answer Y

Single Quotes versus double quotes Basically, variable names are exapnded within double quotes, but not single quotes. If you do not need to refer to variables, single quotes are good to use as the results are more predictable. Example: #!/bin/bash echo -n '$USER=' # -n option stops echo from breaking the line echo "$USER" echo "\$USER=$USER" # this does the same thing as the first two lines The output looks like this (assuming your username is Student) $USER=Student $USER=Student So the double quotes still have a work around. Double quotes are more flexible, but less predictable. Given the choice between single quotes and double quotes, use single quotes.

Command Substituation The backquote “`” is different from the single quote “´”. It is used for command substitution: `command` $ LIST=`ls` $ echo $LIST hello.sh read.sh PS1=“`pwd`>” /home/rinaldi/didattica/> We can perform the command substitution by means of $(command) $ LIST=$(ls) $ echo $LIST hello.sh read.sh rm $( find / -name “*.tmp” ) ls $( pwd ) ls $( echo /bin )

Arithmetic The let statement can be used to do mathematical functions: $ let X=10+2*7 $ echo $X 24 $ let Y=X+2*4 $ echo $Y 32 An arithmetic expression can be evaluated by $[expression] or $((expression)) $ echo $((123+20)) 143 $ VALORE=$[123+20] $ echo $[123*$VALORE] 1430 $ echo $[2**3] $ echo $[8%3]

Example Example (operations.sh) #!/bin/bash echo -n “Enter the first number: ”; read x echo -n “Enter the second number: ”; read y add=$(($x + $y)) sub=$(($x - $y)) mul=$(($x * $y)) div=$(($x / $y)) mod=$(($x % $y)) # print out the answers: echo “Sum: $add” echo “Difference: $sub” echo “Product: $mul” echo “Quotient: $div” echo “Remainder: $mod”

If statement Conditionals let we decide whether to perform an action or not, this decision is taken by evaluating an expression. The most basic form is: if [expression]; then statements elif [expression]; then statements else statements fi the elif (else if) and else sections are optional

If Statement An expression can be: String comparison, Numeric comparison, File operators and Logical operators and it is represented by [expression]: String Comparisons: = compare if two strings are equal != compare if two strings are not equal -n evaluate if string length is greater than zero -z evaluate if string length is equal to zero Examples: [ s1 = s2 ] (true if s1 same as s2, else false) [ s1 != s2 ] (true if s1 not same as s2, else false) [ s1 ] (true if s1 is not empty, else false) [ -n s1 ] (true if s1 has a length greater then 0, else false) [ -z s2 ] (true if s2 has a length of 0, otherwise false)

Example #!/bin/bash # if0.sh echo -n “Enter your login name: " read name if [ “$name” = “$USER” ]; then echo “Hello, $name. How are you today ?” else echo “You are not $USER, so who are you ?” fi #!/bin/bash # if1.sh echo -n “Enter a number 1 < x < 10: " read num if [ “$num” -lt 10 ];then if [ “$num” -gt 1 ]; then echo “$num*$num=$(($num*$num))” else echo “Wrong insertion !” fi else echo “Wrong insertion !” fi