Command Substitution Command substitution is the mechanism by which the shell performs a given set of commands and then substitutes their output in the.

Slides:



Advertisements
Similar presentations
Shell Scripting Printing; Loops and Logic printf: formatted print printf is a more standardized method to print text to the screen. It can be used instead.
Advertisements

CIS 240 Introduction to UNIX Instructor: Sue Sampson.
Linux Shell Script. Shell script The first line is used to specify shell program #!/bin/sh Variables variable=“text” variable=0 variable=`program arguments`
Introduction to Unix – CS 21 Lecture 11. Lecture Overview Shell Programming Variable Discussion Command line parameters Arithmetic Discussion Control.
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.
CS 497C – Introduction to UNIX Lecture 33: - Shell Programming Chin-Chih Chang
Bash, part 2 Prof. Chris GauthierDickey COMP Unix Tools.
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. Shell Scripts (1) u Basically, a shell script is a text file with Unix commands in it. u Shell scripts usually begin with a #! and.
Lab 8 Shell Script Reference:
Shell Control Structures CSE 2031 Fall August 2015.
Agenda Control Flow Statements Purpose test statement if / elif / else Statements for loops while vs. until statements case statement break vs. continue.
Chapter 5 Bourne Shells Scripts By C. Shing ITEC Dept Radford University.
The if construct The general format of the if command is: Every command has exit status If the exit status is zero, then the commands that follow between.
Bash shell programming Part II – Control statements Deniz Savas and Michael Griffiths November 2005 Corporate Information and Computing Services The University.
Shell Script Programming. 2 Using UNIX Shell Scripts Unlike high-level language programs, shell scripts do not have to be converted into machine language.
Linux+ Guide to Linux Certification, Third Edition
Linux Operations and Administration
CMPSC 60: Week 6 Discussion Originally Created By: Jason Wither Updated and Modified By: Ryan Dixon University of California Santa Barbara.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM. 5.1 © Copyright IBM Corporation 2008 Unit 11: Shell.
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.
1 © 2001 John Urrutia. All rights reserved. Chapter 10 using the Bourne Again Shell.
Shell Programming. Creating Shell Scripts: Some Basic Principles A script name is arbitrary. Choose names that make it easy to quickly identify file function.
Chapter 10: BASH Shell Scripting Fun with fi. In this chapter … Control structures File descriptors Variables.
Shells. Variables MESSAGE="HELLO WORLD" echo $MESSAGE MESSAGE="HELLO WORLD $LOGNAME" echo $MESSAGE MESSAGE="HELLO WORLD $USER" echo $MESSAGE.
(A Very Short) Introduction to Shell Scripts CSCI N321 – System and Network Administration Copyright © 2000, 2003 by Scott Orr and the Trustees of Indiana.
1 P51UST: Unix and Software Tools Unix and Software Tools (P51UST) More Shell Programming Ruibin Bai (Room AB326) Division of Computer Science The University.
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.
Xuan Guo Chapter 5 The Bourne Shell Graham Glass and King Ables, UNIX for Programmers and Users, Third Edition, Pearson Prentice Hall, Notes by Michael.
1 © 2000 John Urrutia. All rights reserved. Session 5 The Bourne Shell.
Shell Script2 Reference: Linux Shell Scripting Tutorial v1.05r3 A Beginner's handbook
Agenda Positional Parameters / Continued... Command Substitution Bourne Shell / Bash Shell / Korn Shell Mathematical Expressions Bourne Shell / Bash Shell.
Flow Control. The order in which commands execute in a shell script is called the flow of the script. When you change the commands that execute based.
Lab 8 Shell Script Reference: Linux Shell Scripting Tutorial v1.05r3 A Beginner's handbook
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]
Chapter 5 The Bourne Shell Graham Glass and King Ables, UNIX for Programmers and Users, Third Edition, Pearson Prentice Hall, Notes by Michael Weeks.
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.
Chapter 16 Advanced Bourne Shell Programming. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Objectives To discuss numeric data processing.
Linux Administration Working with the BASH Shell.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
1 Lecture 8 Shell Programming – Control Constructs COP 3353 Introduction to UNIX.
Chapters 13 and 14 in Quigley's "UNIX Shells by Example"
COMP075 OS2 Bash Scripting. Scripting? BASH provides access to OS functions, like any OS shell Also like any OS shell, BASH includes the ability to write.
Bash Shell Scripting 10 Second Guide.
Agenda Bash Shell Scripting – Part II Logic statements Loop statements
CSC 352– Unix Programming, Fall 2012
Shell Scripting March 1st, 2004 Class Meeting 7.
EGR 2261 Unit 4 Control Structures I: Selection
Agenda Control Flow Statements Purpose test statement
Pepper (Help from Dr. Robert Siegfried)
Topics Introduction to File Input and Output
Copyright © – Curt Hill Bash Flow of Control Copyright © – Curt Hill.
Linux Shell Script Programming
Presented by, Mr. Satish Pise
Chapter 5 The Bourne Shell
CSC 352– Unix Programming, Fall, 2011
Shell Control Structures
Chapter 5 Bourne Shells Scripts
The Selection Structure
Essential Shell Programming
Introduction to Bash Programming, part 3
Topics Introduction to File Input and Output
Basic shell scripting CS 2204 Class meeting 7
Review.
Review The Unix Shells Graham Glass and King Ables,
Presentation transcript:

Command Substitution Command substitution is the mechanism by which the shell performs a given set of commands and then substitutes their output in the place of the commands. Command substitution is performed when a command is given as ´command´ Here command, can be a simple command, a pipeline, or a list. Caution - Make sure that you are using the backquote, not the single quote character, when performing command substitution. Command substitution is performed by the shell only when the backquote, or backtick, character, ´, is given. Using the single quote instead of the back quote is a common error in shell scripts leading to many hard to find bugs.

Command substitution is generally used to assign the output of a command to a variable. Each of the following examples demonstrate command substitution: DATE=´date´ USERS=´who | wc -l´ UP=´date ; uptime´ In the first example, the output of the date command becomes the value for the variable DATE. In the second example, the output of the pipeline becomes the value of the variable USERS. In the last example, the output of the list becomes the value of the variable UP.

Arithmetic Substitution In ksh and bash, the shell enables integer arithmetic to be performed. This avoids having to run an extra program such as expr or bc to do math in a shell script. This feature is not available in sh. Arithmetic substitution is performed when the following form of command is given: $((expression)) Expressions are evaluated according to standard mathematical conventions. Table 8.3 provides the available operators. The operators are listed in order of precedence.

Table 8.3 Arithmetic Substitution Operators Operator Description / The division operator. Divides two numbers and returns the result. * The multiplication operator. Multiples two numbers and returns the result. - The subtraction operator. Subtracts two numbers and returns the result. + The addition operator. Adds two numbers and returns the result. () The parentheses clarify which expressions should be evaluated before others. You use the following command as an illustration of the operators and their precedence: foo=$(( ((5 + 3*2) - 4) / 2 )) After this command executes the value of foo to 3. Because this is integer arithmetic, the value is not 3.5, and because of operator precedence the value is not 6.

Flow Control if Statement The if statement performs actions depending on whether a given condition is true or false. Because the return code of a command indicates true (return code is zero) or false (return code is nonzero), one of the most common uses of the if statement is in error checking. An example of this is covered shortly. The basic if statement syntax follows: if list1 then list2 elif list3 list4 else list5 fi

Both the elif and the else statements are optional Both the elif and the else statements are optional. If you have an elif statement, you don't need an else statement and vice versa. An if statement can be written with any number of elif statements. The flow control for the general if statement follows: list1 is evaluated. 2. If the exit code of list1 is 0, indicating a true condition, list2 is evaluated and the if statement exits. 3. Otherwise, list3 is executed and its exit code is checked. 4. If list3 returns 0, list4 executes and the if statement exits. 5. If list3 does not return 0, list5 executes.

Because the shell considers an if statement to be a list, you can write it all in one line as follows: if list1 ; then list2 ; elif list3 ; then list4 ; else list5 ; fi ; Usually this form is used only for short if statements.

if uuencode koala.gif koala.gif > koala.uu ; then Example A simple use of the if statement is if uuencode koala.gif koala.gif > koala.uu ; then echo "Encoded koala.gif to koala.uu" else echo "Error encoding koala.gif" Fi Look at the flow of control through this statement: 1. First, the command uuencode koala.gif koala.gif > koala.uu executes. This command is list1 in the general statement. 2. If this command is successful, the command uuencode Command Purpose Encodes a binary file for transmission using electronic mail. Syntax uuencode [ -m ] [ SourceFile ] OutputFile Description The uuencode command converts a binary file to ASCII data. This is useful before using BNU (or uucp) mail to send the file to a remote system. The uudecode command converts ASCII data created by the uuencode command back into its original binary form. The uuencode command takes the named SourceFile (default standard input) and produces an encoded version on the standard output. The encoding uses only printable ASCII characters, and includes the mode of the file and the OutputFile filename used for recreation of the binary image on the remote system. Use the uudecode command to decode the file. Flags -m Encode the output using the MIME Base64 algorithm. If -m is not specified, the old uuencode algorithm will be used.Parameters OutputFile Specifies the name of the decoded file. You can direct the output of the uuencode command to standard output by specifying /dev/stdout as the OutputFile.SourceFileSpecifies the name of the binary file to convert. Default is standard input.

executes and the if statement exits executes and the if statement exits. This command is list2 in the general statement. 3. Otherwise the command echo "Error encoding koala.gif“ executes, and the if statement exits. This command is list5 in the general statement. You might have noticed in this example that both the if and then statements appear on the same line. Most shell programmers prefer to write if statements this way in order to make the if statement more concise. The majority of shell programmers claim that this form looks better.

Common Errors Three common errors can occur when using the if statement: Omitting the semicolon ( ;) before the then statement in the single line form Using else if or elsif instead of elif. Omitting the then statement when an elif statement is used. Writing if instead of fi at the end of an if statement.

Using test Most often, the list given to an if statement is one or more test commands, which are invoked by calling the test command as follows: test expression Here expression is constructed using one of the special options to the test command. The test command returns either a 0 (true) or a 1 (false) after evaluating an expression. A shorthand for the test command is the [ command: [ expression ] Here expression is any valid expression that the test command understands. This shorthand form is the most common form of test that you can encounter.

The types of expressions understood by test can be broken into three types: File tests String comparisons Numerical comparisons

File Tests File test expressions test whether a file fits some particular criteria. The general syntax for a file test is test option file or [ option file ] Here option is one of the options given in Table 10.1 and file is the name of a file or directory. Look at a few examples of if statements that use the test command to perform file tests. Consider the following if statement: $ if [ -d /home/ranga/bin ] ; then PATH="$PATH:/home/ranga/bin" ; fi Here you are testing whether the directory /home/ranga/bin exists. If it does, append it to the variable PATH. Similar statements are often encountered in shell initialization scripts such as .profile or .kshrc.

Say you want to execute commands stored in the file $HOME/ Say you want to execute commands stored in the file $HOME/.bash_aliai if it exists. You can use the command $ if [ -f $HOME/.bash_aliai ] ; then . $HOME/.bash_aliai ; fi An improvement on this would be to test whether the file has any content and, if so, run the commands stored in it. You can change the command to use the - s option instead of the - f option to achieve this result: if [ -s $HOME/.bash_aliai ] ; then . $HOME/.bash_aliai ; fi Now the commands stored in the file $HOME/.bash_aliai execute if that file exists and has some content.

File Test Options for the test Command Option Description -b file True if file exists and is a block special file. -c file True if file exists and is a character special file. -d file True if file exists and is a directory. -e file True if file exists. -f file True if file exists and is a regular file. -g file True if file exists and has its SGID bit set. -h file True if file exists and is a symbolic link. -k file True if file exists and has its "sticky" bit set. -p file True if file exists and is a named pipe. -r file True if file exists and is readable. -s file True if file exists and has a size greater than zero. -u file True if file exists and has its SUID bit set. -w file True if file exists and is writable. -x file True if file exists and is executable. -O file True if file exists and is owned by the effective user ID.

String Comparisons The test command also supports simple string comparisons. There are two main forms: 1. Checking whether a string is empty 2. Checking whether two strings are equal The test options relating to string comparisons are given in Table 10.2. Table 10.2 String Comparison Options for the test Command Option Description -z string True if string has zero length. -n string True if string has nonzero length. string1 = string2 True if the strings are equal. string1 != string2 True if the strings are not equal.

Numerical Comparisons The test command enables you to compare two integers. The basic syntax is test int1 operator int2 or [ int1 operator int2 ] Here int1 and int2 can be any positive or negative integers and operator is one of the operators given in Table 10.3. If either int1 or int2 is a string, not an integer, it is treated as 0

Operator Description int1 -eq int2 True if int1 equals int2. int1 -ne int2 True if int1 is not equal to int2. int1 -lt int2 True if int1 is less than int2. int1 -le int2 True if int1 is less than or equal to int2. int1 -gt int2 True if int1 is greater than int2. int1 -ge int2 True if int1 is greater than or equal to int2

Case The case Statement The case statement is the other major form of flow control available in the shell. . The basic syntax is case word in pattern1) list1 ;; pattern2) list2 esac

Here the string word is compared against every pattern until a match is found. The list following the matching pattern executes. If no matches are found, the case statement exits without performing any action. There is no maximum number of patterns, but the minimum is one.

A case Statement Example Consider the following variable declaration and case statement: FRUIT=kiwi case "$FRUIT" in apple) echo "Apple pie is quite tasty." ;; banana) echo "I like banana nut bread." ;; kiwi) echo "New Zealand is famous for kiwi." ;; Esac

The execution of the case statement is as follows: 1. The string contained in the variable FRUIT is expanded to kiwi. 2. The string kiwi is compared against the first pattern, apple. Because they don't match, you go to the next pattern. 3. The string kiwi is compared against the next pattern, banana. Because they don't match, you go 4. The string kiwi is compared against the final pattern, kiwi. Because they match, the following message is produced: New Zealand is famous for kiwi.

The while Loop The basic syntax of the while loop is while command do list Done Here command is a single command to execute, whereas list is a set of one or more commands to execute. list is commonly referred to as the body of the while loop because it contains the heart or guts of the loop. The do and done keywords are not considered part of the body of the loop because the shell uses them only for determining where the while loop begins and ends.

The execution of a while loop proceeds according to the following steps: 1. Execute command. 2. If the exit status of command is nonzero, exit from the while loop. 3. If the exit status of command is zero, execute list. 4. When list finishes executing, return to Step 1.

Here is a simple example that uses the while loop to display the numbers zero to nine: while [ $x -lt 10 ] do echo $x x=´echo "$x + 1" | bc´ done Its output looks like this: 1 2 . 9

The until Loop until command do list done The while loop is perfect for a situation where you need to execute a set of commands while some condition is true. Sometimes you need to execute a set of commands until a condition is true. A variation on the while loop available only in ksh and bash, the until loop provides this functionality. Its basic syntax is: until command do list done Here command is a single command to execute, whereas list is a set of one or more commands to execute.

The execution of an until loop is identical to that of the while loop and proceeds according to the following steps: Execute command. 2. If the exit status of command is nonzero, exit from the until loop. 3. If the exit status of command is zero, execute list. 4. When list finishes executing, return to Step 1.

In most cases the until loop is identical to a while loop with list1 negated using the ! operator. For example, the following while loop x=1 while [ ! $x -ge 10 ] do echo $x x=´echo "$x + 1" | bc´ done is equivalent to the following until loop: x=1; until [ $x -ge 10 ] The until loop offers no advantages over the equivalent while loop. Because it isn't supported by all versions of the Bourne shell, programmers do not favor it. I have covered it here because you might run across it occasionally.