Introduction to UNIX / Linux - 11 Dr. Jerry Shiao, Silicon Valley University Summer 2015 SILICON VALLEY UNIVERSITY CONFIDENTIAL
Introduction UNIX/Linux Course Section 11 Advanced Bourne Shell Programming Numeric Data Processing. Redirect stdin to Data Within the Script. Here Document. Signal / Interrupt Processing. File I/O using File Descriptors. Redirect Standard Files Within the Script. Functions in Bourne Shell and Scripts. Debugging Bourne Shell Scripts. Summer 2015 SILICON VALLEY UNIVERSITY CONFIDENTIAL
Introduction UNIX/Linux Course Section 11 Bourne Shell Variables Stored as character string ConvertInt Num Operation ConvertChar To perform arithmetic and logic operations, convert shell variables to integers and the result convert back to character string. expr Shell Command expr args Evaluate the expression arguments, “args”, and send the result to standard output. Copyright @2005 Pearson Addison-Wesley SILICON VALLEY UNIVERSITY CONFIDENTIAL
Introduction UNIX/Linux Course Section 11 Bourne Shell Variables expr Shell Command Commonly used operators/features: Need escape character “\” to use metacharacters (|, &, >, <, *). \| return the first expression if it is not null or 0; else return the second expression \& Return the first expression if neither is null or 0;else return 0 =, \>, \>=, Integer comparison operators;equal, \<, \<=,!= greater than, greater than or equal to, less than ,less than or equal to , not equal +, -, \*, /, % Integer arithmetic operators, add , subtract, multiply, integer divide (return quotient), remainder Copyright @2005 Pearson Addison-Wesley SILICON VALLEY UNIVERSITY CONFIDENTIAL
Introduction UNIX/Linux Course Section 11 Bourne Shell Variables expr Shell Command $ var1=10 $ var1=`expr $var1 + 1` $ echo $var1 11 $ var1=`expr $var1 \* $var1` 121 $ echo `expr $var1 / 10` 12 $ echo `expr $var1 % 10` 1 $ $var1 + 1 <10> + 1 = 11 $var1 * $var1 <11> * <11> = 121 $var1 / 10 <121> / 10 = 12 $var1 % 10 <121> % 10 = 1 Copyright @2005 Pearson Addison-Wesley SILICON VALLEY UNIVERSITY CONFIDENTIAL
Introduction UNIX/Linux Course Section 11 Bourne Shell Variables $ cat countup #!/bin/sh if [ $# != 1 ] then echo "Usage $0 integer-argument" exit 1 fi target="$1" # Set target to the number passed at the command line. current=1 # The first number to be displayed. # Loop here until the current number becomes greater than the target while [ $current -le $target ] do echo "$current \c" current=`expr $current + 1` done echo exit 0 $ countup 5 1 2 3 4 5 $#: Number of argumentds. $0: File name. Check $current less than and equal to $target Expr increments the variable current. Copyright @2005 Pearson Addison-Wesley SILICON VALLEY UNIVERSITY CONFIDENTIAL
Introduction UNIX/Linux Course Section 11 Bourne Shell Variables To Create Standard Input Data for Commands in the Script. here document Redirect standard input of a command in the script and define the redirected data (inbetween “input-marker”s) in the script. “ – “ : Removes leading tabs (not spaces) from the line (allows text in here document to have tabs). Copyright @2005 Pearson Addison-Wesley SILICON VALLEY UNIVERSITY CONFIDENTIAL
Introduction UNIX/Linux Course Section 11 Bourne Shell Variables The here document is enclosed within “DataTag” markers. The here document is enclosed within “WRAPPER” markers. Copyright @2005 Pearson Addison-Wesley SILICON VALLEY UNIVERSITY CONFIDENTIAL
Introduction UNIX/Linux Course Section 11 Bourne Shell Variables The here document is enclosed within “DIRECTORY” markers. Copyright @2005 Pearson Addison-Wesley SILICON VALLEY UNIVERSITY CONFIDENTIAL
Introduction UNIX/Linux Course Section 11 Bourne Shell Interrupt Signal Processing Software Interrupt Process Actions: Accept the default action as defined by the UNIX Kernel. Ignore the signal. Process signal with programmer-defined action. Software Interrupts: Termination of process (<Ctrl-C>, user logout). Termination of child process. Memory fault when process access invalid memory address. Software “kill” command, Hardware Interrupts: Keyboard interrupt. Copyright @2005 Pearson Addison-Wesley SILICON VALLEY UNIVERSITY CONFIDENTIAL
Introduction UNIX/Linux Course Section 11 Bourne Shell Interrupt Signal Processing Copyright @2005 Pearson Addison-Wesley SILICON VALLEY UNIVERSITY CONFIDENTIAL
Introduction UNIX/Linux Course Section 11 Bourne Shell Interrupt Signal Processing Intercept Signals trap [‘command-list’] [signal-list] trap command used to ignore signals or execute sequence of commands when certain signals are received. trap with no arguments uses default actions. ‘ ‘ : No command-list means ignore “signal-list” signals. ‘command-list’ : Executes “command-list” when “signal-list” signals are received. Copyright @2005 Pearson Addison-Wesley SILICON VALLEY UNIVERSITY CONFIDENTIAL
Introduction UNIX/Linux Course Section 11 Bourne Shell Interrupt Signal Processing #!/bin/sh # Intercept signals and ignore them trap '' 1 2 3 15 18 secretcode=agent007 echo “Guess the code!” echo “Enter your guess: \c” read yourguess while [ “$secretcode” != “$yourguess” ] do echo “Good guess but wrong. Try again!” done echo “Wow! You are a genius!!” exit 0 The double quote means ignore traps. Disables SIGINT(2) <Ctrl-C>. Enter <Ctrl-C> does not exit the shell script. $ ./while_demo “Guess the code!” “Enter your guess: c” C-c C-c agent007 “Wow! You are a genius!!” $ Copyright @2005 Pearson Addison-Wesley SILICON VALLEY UNIVERSITY CONFIDENTIAL
Introduction UNIX/Linux Course Section 11 Execute Command Replacing Shell Process exec command “command” image replaces the shell image and executes. “command” process exit returns to the parent of the calling process. If calling process is login shell, “command” process exits to the getty process and user has to login again. Used with redirection operators, the commands and shell scripts can read/write any type of files. Used for: To execute a command/program instead of the current process (under which exec is executed). To open and close file descriptors. Copyright @2005 Pearson Addison-Wesley SILICON VALLEY UNIVERSITY CONFIDENTIAL
Introduction UNIX/Linux Course Section 11 Execute Command Replacing Shell Process exec command Exec returns to the parent (getty) of the calling process (shell). Copyright @2005 Pearson Addison-Wesley SILICON VALLEY UNIVERSITY CONFIDENTIAL
Introduction UNIX/Linux Course Section 11 Execute Command Replacing Shell Process exec command Run under subshell, control goes back to the parent shell (normally the login shell). Start the subshell ( C Shell ). Exec runs in the subshell, returns to the parent of the subshell. Since exec ‘date’ image overwrote the calling process image ( C Shell), returns to the parent ( bash Shell). Copyright @2005 Pearson Addison-Wesley SILICON VALLEY UNIVERSITY CONFIDENTIAL
Introduction UNIX/Linux Course Section 11 Execute Command Replacing Shell Process exec command Run under subshell, control goes back to the parent shell (normally the login shell). Exec runs in the subshell, replace the calling process image (the subshell). Replaced by exec. Copyright @2005 Pearson Addison-Wesley SILICON VALLEY UNIVERSITY CONFIDENTIAL
Introduction UNIX/Linux Course Section 11 exec command and File I/O Exec allows reassignment of stdin(0), stdout(1), and stderr(2) to files. Files can be assign File Descriptor (3 - 9) File Descriptors 0 – 9 exec < sample Opens “sample” for reading and attaches to standard input of the process. Each line in “sample” is treated as a command and executed by the current shell. exec > data Opens “data” for writing and attaches to standard output of the process. Output of all subsequent commands executed under the shell to go to “data” file. Copyright @2005 Pearson Addison-Wesley SILICON VALLEY UNIVERSITY CONFIDENTIAL
Introduction UNIX/Linux Course Section 11 exec command and File I/O Copyright @2005 Pearson Addison-Wesley SILICON VALLEY UNIVERSITY CONFIDENTIAL
Introduction UNIX/Linux Course Section 11 exec command and File I/O File “sample” contains commands. The exec command redirects the stdin file to “sample” and Bourne shell executes commands in “sample”. Copyright @2005 Pearson Addison-Wesley SILICON VALLEY UNIVERSITY CONFIDENTIAL
Introduction UNIX/Linux Course Section 11 exec command and File I/O Redirect stdin to “sample. Copyright @2005 Pearson Addison-Wesley SILICON VALLEY UNIVERSITY CONFIDENTIAL
Introduction UNIX/Linux Course Section 11 exec command and File I/O exec > /dev/tty Reconnects stdout to console. exec < /dev/tty Reconnects stdin to keyboard. $ exec > data $ date $ echo Hello, World! $ uname -a $ exec > /dev/tty $ cat data Tue Dec 11 23:13:09 PST 2012 Hello, World! Linux buildbed-vm 2.6.34.10-0.6-pae #1 SMP 2011-12-13 18:27:38 +0100 i686 i686 i386 GNU/Linux $ Redirects stdout to “data”. All output appended to “data” file. Reconnects stdout to console ( /dev/tty ). Copyright @2005 Pearson Addison-Wesley SILICON VALLEY UNIVERSITY CONFIDENTIAL
Introduction UNIX/Linux Course Section 11 exec command and File I/O Sent to file1. Sent to file4. Copyright @2005 Pearson Addison-Wesley SILICON VALLEY UNIVERSITY CONFIDENTIAL
Introduction UNIX/Linux Course $cat diff2 #!/bin/sh # Purpose: To see if the two files passed as command line arguments are same or # different. # Description: Read a line from each file and compare them. If the lines are the same, # continue. If they are different, display the two lines and exit. If one of the files # finishes before the other, display a message and exit. Otherwise, the files are # the same; display an appropriate message and exit. If [ $# != 2 ] then echo “Usage: $0 file1 file2” exit 1 elif [ ! -f “$1” ] echo “$1 is not an ordinary file” elif [ ! -f “$2” ] echo “$2 is not an ordinary file” exit 1 else : fi Spaces MUST be before and after the “]” and the operators. Expand $1 and $2 to verify passed parameters are ordinary files. Copyright @2005 Pearson Addison-Wesley SILICON VALLEY UNIVERSITY CONFIDENTIAL
Introduction UNIX/Linux Course Set File Descriptor 3 to $file1 and FD 4 to $file2. file1=“$1” file2=“$2” exec 3< “$file1” exec 4< “$file2” while read line1 0<&3 do if read line2 0<&4 then if [ “$line1” != “$line2” ] echo “$1: $line1 and $2: $line2 are different.” exit 1 fi else echo “$1 and $2 are different and $1 is larger than $2” done Read will read into shell variable $line1. In until statement, read status return 0 (TRUE) unless EOF is reached. Read will read into shell variable $line2. In until statement, read status return 0 (TRUE) unless EOF is reached. EOF is reached. Since $file1 has read a line, $file2 is smaller than $file1. Copyright @2005 Pearson Addison-Wesley SILICON VALLEY UNIVERSITY CONFIDENTIAL
Introduction UNIX/Linux Course EOF has been reached in $file1. Read $file2 to check if EOF is also reached. if read line2 0<&4 then echo “$1 and $2 are different and $2 is bigger than $1.” exit 1 else echo “$1 and $2 are the same!” exit 0 fi exec 3<&- exec 4<&- EOF in $file2 has NOT been reached. Since $file1 has reached EOF, $file2 is larger than $file1. EOF has been reached in $file1. EOF is also reached in $file2. Close $file1 ( File Descriptor 3 ). Close $file2 ( File Descriptor 4 ). Copyright @2005 Pearson Addison-Wesley SILICON VALLEY UNIVERSITY CONFIDENTIAL
Introduction UNIX/Linux Course Section 11 Bourne Shell and Functions Function contains Function Name and Body. Function Body consists of group of commands that could be executed at multiple places in script. Function Name executes Function Body. Transferring the control to the function code and returning control to the calling code takes time. Create another script file for the group of commands and invoke this code by calling the script. Functions normally placed in script file that uses the function. Functions can be exported to make function available to all child processes of the process. Copyright @2005 Pearson Addison-Wesley SILICON VALLEY UNIVERSITY CONFIDENTIAL
Introduction UNIX/Linux Course Section 11 Bourne Shell and Functions Functions placed in login scripts and shell scripts. In ~/.profile file or .bashrc file. Commands in Function Body ONLY executed when Function Name is called. Invoke a function by using the Function Name. Control comes back to the command following the function call. Set command will view all configured functions. Format of function: Function_name ( ) { command-list } Copyright @2005 Pearson Addison-Wesley SILICON VALLEY UNIVERSITY CONFIDENTIAL
Introduction UNIX/Linux Course Section 11 Bourne Shell and Functions $ machines () > { > date > echo “These are the machines on the network:” > ruptime | cut -f1 -d’ ‘ | more > } $ machines Thu Feb 19 17:05:00 PDT 2004 These are the machines on the network: upibm0 ... upsun1 upsun29 $ Function head. Function body begins with “{“ and ends with “}”. Function body entered similar to using continuation line. Copyright @2005 Pearson Addison-Wesley SILICON VALLEY UNIVERSITY CONFIDENTIAL
Introduction UNIX/Linux Course Section 11 Bourne Shell and Functions Debugging Shell Scripts Execute shell script in sh command. - x : Echo option displays each line of the script after variable substition, but before execution. - v : Verbose option displays each line of the script (as in the script file) before execution. Copyright @2005 Pearson Addison-Wesley SILICON VALLEY UNIVERSITY CONFIDENTIAL
Introduction UNIX/Linux Course “ – v “ : Display each line before execution. “ – x “ : Display each line after variable substitution. Has “ + “ preceding the line. Section 11 Bourne Shell and Functions Debugging Shell Scripts Copyright @2005 Pearson Addison-Wesley SILICON VALLEY UNIVERSITY CONFIDENTIAL