1 / 37

Bourne (Again) Shell

Bourne (Again) Shell. CIS 218. Bourne Again Shell. Current GNU LINUX BASH Shell documentation: http://www.gnu.org/software/bash/manual/bashref.html

lobo
Download Presentation

Bourne (Again) Shell

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Bourne (Again) Shell CIS 218

  2. Bourne Again Shell • Current GNU LINUX BASH Shell documentation: http://www.gnu.org/software/bash/manual/bashref.html • Bash is an acronym for ‘Bourne-Again SHell’. The Bourne shell is the traditional Unix shell originally written by Stephen Bourne. All of the Bourne shell builtin commands are available in Bash. Current BASH development occurs under the GNU license OS’es (essentially for LINUX). Which means to use caution when incorporating advanced bash features for portable bash scripts (i.e. sh). • Shell command processing - When the shell reads input, it proceeds through a sequence of operations. If the input indicates the beginning of a comment, the shell ignores the comment symbol (‘#’), and the rest of that line. - The shell reads its input and divides the input into words and operators based on the InterField Separator (IFS) value, employing the quoting rules to select which meanings to assign various words and characters. - The shell then parses these tokens into commands and other constructs, removes the special meaning of certain words or characters, expands others, redirects input and output as needed, executes the specified command, waits for the command’s exit status, and makes that exit status available for further inspection or processing.

  3. Shell Startup • When a shell starts, it runs startup files to initialize itself. Which files the shell runs depends on whether it is a login shell, an interactive shell that is not a login shell (such as you get by giving the command bash), or a noninteractive shell (one used to execute a shell script). You must have read access to a startup file to execute the commands in it. • Interactive LOGIN files: - /etc/profile: The shell first executes the commands in /etc/profile. By default when called from bash, a command in this file calls /etc/bashrc. This file establishes system-wide default characteristics for bash users. -.bash_profile .bash_login .profile:Next the shell looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, executing the commands in the first of these files it finds. Commands in these files to override the defaults set in /etc/profile. - .bash_logout:When you log out, bash executes commands in the ~/.bash_logout file. Frequently commands that clean up after a session, such as those that remove temporary files, go in this file. • Noninteractive Shells, such as those that runs shell scripts. However, these shells inherit from the login shell variables that are set by these startup files. Noninteractive shells look for the environment variable BASH_ENV (or ENV, if the shell is called as sh) and execute commands in the file named by this variable.

  4. Shell Environment Variables • PS1 - This parameter is used as the primary prompt string. The default is: \s-\v\$ . • PS2 - The parameter is used as line continuation. The default is: > • PS3 - The value of this parameter is used as the prompt for the select command. • PS4 - This parameter is displayed during an execution trace (sh –x). The default is + • HOME – Stores the home directory • PATH – contains a list of directories which the shell searches whenever you type in the name of the program to be executed. The PATH specifies the directories to be searched for programs to be executed and not for any other types of files.

  5. Shell Operation • Reads its input from a file from a string supplied as an argument to the ‘-c’ invocation option or from the user’s terminal (when <LF> is read). • Breaks the input into words and operators, obeying the quoting rules and metacharacter substitution. These tokens are separated by IFS. Alias expansion is performed. • Parses the tokens into simple and compound commands. • Performs the various shell expansions breaking the expanded tokens into lists of filenames and commands and arguments. • Performs any necessary redirections and removes the redirection operators and their operands from the argument list. • Executes the command. If a command delimiter is used for more than one command on a line (record), commands are executed sequentially. • Optionally waits for the command to complete and collects its exit status

  6. Bash command line operation • Command line editing under the Bourne Again Shell is implemented through the Readline Library which supports line editing that is consistent with that provided by bash. • vi mode: You can choose vi editing modes when using the Readline you can switch to vi mode with the following command: set-o vi • When you enter bash commands while in vi editing mode, you are in Input mode. As you enter a command, if you discover an error before you press RETURN, you can press ESCAPE to switch to vi Command mode. • HJKL keys can be used to change position just like in vi.

  7. eval command • evalcommand – forces shell to scan the command line twice. The internal eval command interprets and expands a command line before the shell interprets and expands the line.  • You can use eval to execute a command you read using the read command. # read CMD cat /etc/group | grep mylogin # eval "$CMD" processes the CMD variable • You can use eval to expand builtin commands. # CMD=`date | wc` # $CMD # fails because the pipe is not expanded usage: date [-a sss.fff] [-u] [tformat] [mmddhhmm[yy]] # eval $CMD # eval expands CMD to date | wc ·You can use eval to force variable redirection multiple times # X=10 # Y=X # echo '$'$Y # results in $X # eval echo '$'$Y # results in 10 # a='$b‘; b='$c‘; c=d # echo $a # results in $b # First level. # eval echo $a # results in $c # Second level. # eval eval echo $a # results in d # Third level. • you can use eval to expand variables within a command line to be the name of another variable. # eval last='$'{$#} # expands to last positional parameter. Note \ can be used in place of single quotes – whatever suppresses initial evaluation of the $.

  8. exec command • execcommand replaces the current process with command without forking a child process istead runs in current process. It is always the last command executed in a script. Variables set in current process move to command. • Used with find command to act upon “found” files specified in {}. As in: find / -name “core” –print –exec rm {} \; • You can force recursion by using exec to call the current command: exec $0 • You can use exec to replace the current shell with another program (or shell); when you exit you will be logged off. This is how LOGIN works. It is also used for “secure” LOGINs to application specific systems. • You can use exec to perform I/O redirection commands for manipulating file descriptors within a script: somescript: exec < inputfile # same as ./somescript < inputfile exec 3< inputfile # Opens inputfile with file descriptor 3 for reading. exec 4> outputfile # Opens outputfile with file descriptor 4 for writing. exec 5<&0 # Makes fd 5 a copy of fd 0 (standard input). exec 6>&p # Attach fd 6 to co-process.

  9. expr command • expr command forces evaluation of the string as a number. Use back quotes to assign expression results to a variable: number=`expr $number + 1` • expr command is also used with back quotes for logical operations (e.g. comparison) b=`expr $x = $y`; echo $b # b is ‘0’ • expr can be used with most mathematical and logical operations supported in conditional statement. String length: STR=abcedfg; LENGTH=`expr $STR : ".*"`; echo $LENGTH expr length $STR String evaluation: if expr "$STR" : "[yY]“; then … String character position: expr index abcdef de Substring: expr substr "Goodnight Ladies" 11 6

  10. xargs • xargs command is designed to construct argument lists and invoke other utility. xargs reads items from the standard input or pipes, delimited by blanks or newlines, and executes the command one or more times with any initial-arguments followed by items read from standard input. Blank lines on the standard input are ignored. • Examples: - echo 1 2 3 4 | xargs echo - echo 1 2 3 4 | xargs -n 2 - find . -name "*core“ -print | xargs /bin/rm -f (same as –exec rm {} \;) - find . -name "*core" -print0 | xargs -0 -I {} mv {} ~/old.cores - xargs (-t) - Hi there - Ctrl D - find . -name '*.c' | xargs grep 'stdlib.h'

  11. exit command • exit [n] -Used to terminate current process with a status code ($?) of n, where n is any positive number with a maximum value of 255 (in older bash versions). • Functions within a script use return [n] to set a value upon return to caller.

  12. trap command • The trap command is used to redirect shell operations based on certain process “signals”. These signals vary by OS and Shell. • trap [-lp] [[arg] sigspec ...] - The command arg is to be read and executed when the shell receives signal(s) igspec. - If arg is absent (and there is a single sigspec) or -, each specified signal is reset to its original disposition (the value it had upon entrance to the shell). - If arg is the null string the signal specified by each sigspec is ignored by the shell and by the commands it invokes. - If arg is not present and –p is supplied, then trap commands associated with each sigspec are displayed. - If only -p is given, trap prints the list of commands associated with each signal. - The -l option causes the shell to print a list of signal names and their corresponding numbers. - sigspec is either a signal name or number defined in <signal.h>. Signal names are case insensitive and the SIG prefix is optional. • See man page on signal.h for signal meanings within specific OS/Shell combinations. Traditionally, signals 1-15 are associated with the hardwired tty terminal processing (see man tty).

  13. Executing Commands • When a command is issued in the bash, the command is evaluated and all substitutions (variables and aliases) are made. If the evaluated command matches a bash special command or a defined function, it is executed (see also eval and exec). • If the command matches a name of an executable (binary) file, the shell (the parent) spawns a new (child) process which runs the binary program. • If the command matches the name of a text file marked executable, the shell assumes that it is a shell procedure. To execute this procedure, the shell spawns a subshell that executes the commands specified in the file. • By default, the shell will search for external commands based on the value of the PATH environment variable. If you specify a path with the command, the shell will not search the path for the specified command. Instead, it only searches the path specified on the command line. The ./tells the shell explicitly to look for an executable file in the working directory. To change the environment so that the shell searches the working directory automatically,

  14. Separating and Grouping Commands • The NEWLINE <LF> it initiates execution of the command preceding it each time you press the RETURN key at the end of a command line. • The semicolon (;) is a command separator that does not initiate execution of a command executes a series of commands sequentially a single command line. Commands separated by a ‘;’ are executed sequentially; the shell waits for each command to terminate in turn. The return status is the exit status of the last command executed. You initiate execution of the sequence of commands by pressing RETURN: $ x ; y ; z • \ Continues a Command on the next line when you enter a long command line and the cursor reaches the right side of the screen. The backslash (\) character quotes, or escapes, the NEWLINE character that follows it so that the shell does not treat the NEWLINE as a command terminator.

  15. Separating and Grouping Commands • The pipe symbol (|) and the background task symbol (&) are also command separators. They do not start execution of a command but do change some aspect of how the command functions. The pipe symbol alters the source of standard input or the destination of standard output. The background task symbol causes the shell to execute the task in the background so you get a prompt immediately and can continue working on other tasks. • Parentheses () are used to group commands. The shell creates a copy of itself, called a subshell, for each group. It treats each group of commands as a job and creates a new process to execute each command . Each subshell (job) has its own environment, meaning that it has its own set of variables with values that can differ from those of other subshells. • AND and OR lists are sequences of one or more pipelines separated by the control operators ‘&&’ and ‘||’, respectively. AND and OR lists are executed with left associativity. • “&” places the preceding job in the backgrond (see job control). The following command line executes commands a and b sequentially in the background while executing c in the background. The shell prompt returns immediately: $ (a ; b) & c &

  16. fork and exec • A command on the command line causes the shell to fork a new process, creating a duplicate of the shell process (a subshell). The new process attempts to exec (execute) the command. • Script commands executed within parentheses are run within a subshell. To execute commands within the current shell, enclose them in braces ('{' and '}'), use exec or preceded by a “.”. • Like fork, the exec routine is executed by the operating system (a system call). If the command is a binary executable program, such as a compiled C program, exec succeeds and the system overlays the newly created subshell with the executable program. • If the command is a shell script, exec fails. When exec fails, the command is assumed to be a shell script, and the subshell runs the commands in the script. Unlike a login shell, which expects input from the command line, the subshell takes its input from a file: the shell script. • If you have a shell script in a file that you do not have execute permission for, you can run the commands in the script by using a bash command to exec a shell to run the script directly.

  17. Variables • A variable is a named location in memory that stores a value. • To assign a value to a variable in the Bourne Again Shell, use the following syntax: [set] VARIABLE=value There can be no whitespace on either side of the equal sign (=). However, the value can contain spaces if properly quoted variables can be unset (removed) or protected readonly • Normal variables are “local” to the process. These can be made known to “child” processes using the export command in the form: export variable(=value) • Use braces {} to delineate the variable name so that it can be included as part of a string. For example: person=alex echo $personander …. Will result in an error, no such variable echo ${person}ander …. Will echo “alexander” • Other uses for braces: ${variable:-default} - use default value ${variable:=default} - set default value : ${variable:=default} - set default value but do not evaluate ${variable:?message} - set error message (quote if spaces)

  18. Arrays • Newer Bash versions provide one-dimensional indexed and associative array variables. Any variable may be used as an indexed array. The declare builtin declare -a name will explicitly declare an array. There is no maximum limit on the size of an array. Indexed arrays are referenced using integers. • [set] name[subscript]=valuesubscript must evaluate to a number greater than or equal to zero. To explicitly declare an array, use • Multiple arrays value assignments are of the form [set] name=(value1 ... valuen) where each value is of the form [subscript]=string. • An element of an array may be referenced using ${name[subscript]}. The braces are required to avoid conflicts with the shell's filename expansion operators. If the subscript is ‘@’ or ‘*’, the word expands to all members of the array name. • ${name[*]} expands to a single word with the value of each array member separated by the first character of the IFS variable. • ${name[@]} expands each element of name to a separate word. • ${#name[subscript]} expands to the length of ${name[subscript]}. • The unset builtin is used to destroy arrays. unset name[subscript] destroys the array element at index subscript.. A subscript of ‘*’ or ‘@’ also removes the entire array.

  19. Bash arithmetic • Operators: + - * / % (modulus) or logic operations = != etc • Newer bash versions also use c shell operators: ++, --, (pre or post) ** (be careful about compatibility with portable scripts in older systems ) • Parentheses () reset priority as in algebra • The oldest way using the expr command to force evaluation of the string as a number. Use back quotes to assign expression results to a variable: number=`expr $number + 1` • Can also use back quote for logical operations (e.g. conditional testing) b=`expr $x = $y` # b is ‘0’ • Other traditional ways to do math under bash: let number=$number+1 number=`echo $number + 1 | bc` …... “bc” supports floating point math • Newer ways of bash arithmetic operations (see sh caveats) ((number = number+1)) number=$((number + 1)) number=$[number + 1]

  20. Logical Expressions • Operators: logical: !, &&, || bitwise operators: ~, &, ^, | bit shift: <<, >> comparison: <=, >=, <, >, ==, != assignement: =, *=, /=, %=, -= <<=, >>=, &=, ^=, |= • Expressions: test condition if [condition] [if] [[condition]] [if] ((condition)) • File Test Conditions -d file file is a directory -f file file is a regular file -e file file exists -z file file is 0 bytes long -r file file is readable -w filefile is writable -x file executable -o file ownership - s file Non-zero size - l file Symbolic link - b file Block special file - c file Character special file

  21. System Variables • Keyword shell variables (environment) have special meaning to the shell and usually have short, mnemonic names assigned by startup scripts like /etc/profile or ~/.bash_profile. • System provide variables like $*, $@, $#, $?, $$ have one-character names (for example, 1, ?, and #) and are referenced (as are all variables) by preceding the name with a dollar sign ($1, $?, and $#). The values of these parameters reflect different status of shell interaction. • $0 Name of the file from which command input is being read. • $1-9 Direct reference to command line arguments • $* All command line arguments • $@ All command line arguments • $# # of command line aruments. • $? Return code of last command • $$ (decimal) process number of the (parent) shell. • $! (decimal) process number of the last background process started

  22. Command line arguments in bash • Whenever you give a command, each argument on the command line becomes the value of a positional parameter. Positional parameters are of the type $0, $1, $2 thru $9. • $0 represents the command name • The set builtin command enables you to assign values to positional parameters directly. Set A B C sets $1 to A, $2 to B, $3 to C etc. • shift - If more than 9 arguments are supplied, arguments 10 and up cannot be directly referenced. - Shift left-shifts the positional parameters by moving value in $2 into $1, $3 into $2 etc. - ($#) gets decremented by one on each shift

  23. Variables and Quoting • The shell substitutes the value of a variable when you precede the name of the variable with a dollar sign ($). The command echo $person displays the value of the variable person; it does not display $person because the shell recognizes $person as the name of a variable and substitutes the value of the variable. • Usually the value assigned to a variable is terminated with a whitespace character or IFS. Variables allow imbedded whitespace characters by using quotes. • Doublequotes “” allow for variable substitution with imbedded whitespace characters. person=“alex”; person=“$person + jenny” • Singlequotes ‘’ do not allow for variable substitution with imbedded whitespace characters. person=‘alex and jenny’ • Back quotes or “grave” - `` look like singlequotes below Esc key but are used to assign command output to a variable as a value. See command substitution. person=`echo alex and jenny`

  24. Variables and Quoting • You can also prevent variable substitution by quoting the leading $ with an “escape” or backslash (\): echo \$person • When you reference a variable that contains TABs or multiple adjacent SPACEs, you need to use quotation marks to preserve the spacing. If you do not quote the variable, the shell collapses each string of blank characters into a single SPACE before passing the variable to the utility: person="alex and jenny" • Brace {} expansion: Brace expansion is a bash feature, originating in csh, that allows arbitrary strings to be generated using a similar technique to filename expansion. The results of each expanded string are not sorted and left to right order is preserved. echo a{p,c,d,b}e; ape ace ade abe • Brace expansion should not be used in portable shell scripts (i.e. sh) , because a traditional shell will not produce the same output: echoa{p,c,d,b}e; a{p,c,d,b}e • Braces are also used to delineate variables from adjacent strings that would otherwise generate an error: • person=alex; echo ${person}ander alexander

  25. Shell Scripts • A shell script is a text file made executable that contains valid UNIX and/or shell commands. • #! as the first two characters of a script, the system interprets the characters that follow as the absolute pathname of the utility that should execute the script. This can be the pathname of any program, not just a shell. For example: #!/bin/bash • Script commands executed within parentheses are run within a subshell. To execute commands within the current shell, enclose them in braces ('{' and '}'), use exec or preceded by a “.”. Bash builtin commands do not generate a child process, always run in the current process. • A file is made executable specifying the CHange MODe (CHMOD) command setting the last mode bit to 1. (Example: chmod 755 script_file.sh) unless invoked specifically by a bash command in which case is is provided as input to STDIN. The script must be readable to be executable • Note that all BASH script commands can also be executed directly from the shell prompt as well as a shell script file. • In addition to the commands you would ordinarily use on the command line, control flow commands (also called control structures) find most of their use in shell scripts. This group of commands enables you to alter the order of execution of commands in a script just as you would alter the order of execution of statements using a structured programming language.

  26. Shell Script Debugging • Tracing Mechanisms It is possible to have a trace made of the BourneShell script as it executes. This is invaluable for debugging purposes. All that is required is to give an option to the BourneShell. This is done by including an option on the call to "sh". The command to do this is: sh [-acefhiknrstuvx] [args] • The option to turn on tracing is -x. -v allows for display of commands before substitution. For an example, sh -vx script.sh • The commands as read from the BourneShell script are indicated by the plus sign (+). The next line or lines are the results of the execution of the command. Using this tracing option allows you to se the execution of each command in the script and see the results of that execution.

  27. Bourne Shell Control Structures • Conditions – if, until, while • File Test Conditions -d file file is a directory -f file file is a regular file -e file file exists -z file file is 0 bytes long -r file file is readable -w filefile is writable -x file executable -o file ownership - s file Non-zero size - l file Symbolic link - b file Block special file - c file Character special file • Operators for integer comparisons • eq (equal), -ge (greater than or equal), -gt (greater than), le (less than or equal), -lt (less than) and –ne (not equal) • Operators for string comparisons • = , !=, -n (string is not null) and –z (string is null)

  28. Bourne Shell Control Structures • The for command lets you execute a specified list of commands. The syntax for this command is: for identifier [in list ...] do command[s] done where identifier is a variable which is assigned the value(s) specified by word ... and executes the commands specified by list. If the word option is not specified, the shell executes the list of commands for each positional parameter that is set. • You can also use an if construct to specify conditions in the script. The syntax for this command is: if [test] [condition(s)] then command(s) [elif condition] ... [else command(s)] fi where the commands specified by command(s) are executed if the last condition has a return value of zero. The elif construct represents an else if phrase and the corresponding commands are executed if the previous condition returns a non zero value and the last command executed by the condition following the elif phrase returns a value of zero. The else clause is executed only if all other conditions are return non-zero values. See test command for condition values and syntax.

  29. Bourne Shell Control Structures • The case command can be used to execute commands based on a particular setting of another variable. The syntax for this command is: case word in pattern [| pattern] ...) list;; [pattern [|pattern]...) list;;] esac where word is the variable to match with one of the specified patterns. When a matching pattern is found, the commands specified by list are executed. The vertical bar is used to denote an "or" operation. • The while clause can be used to execute a list of commands while a certain condition holds true. The syntax for the while command is: while [condition] do command(s) done where the command(s) if the last command specified by the conditions returns a zero value. The shell will continue to execute the commands until the last return code specified in condition returns a non-zero value.

  30. Bourne Shell Control Structures • The until command works like the while command except the return values are reversed. This means the commands in list are executed as long as the last command specified by condition returns a non-zero value. This repeats until the last command in condition returns a zero value. until [condition] do command(s) done • Changing default “loop” action in for, switch, while and until - break: to break out of a loop. - break n: to break out of n inner most loops - continue: the remaining commands in the loop are skipped. Start loop again at next value.

  31. Bourne Shell Control Structures • Function Definition A function is a set of repeated commands; out of sequence with rest of the script. You call a function as you would any other command. Syntax is specify the name of the function followed by a set of parenthesis. The commands that are associated with the name should follow, and be enclosed within braces and separated by semi-colons. The syntax for this is: functioname () {command(s);} where functionname is the name of the function and command(s) is a set of commands that are executed when the function is invoked. Functions within a script use return [n] to set a value upon return to caller.

  32. Bourne Shell Control Structures • Keyboard Input You can obtain keyboard input from a bash shel by using the read command as follows: read line This will pause the script and wait for keyboard input all of which is assigned to the varialble line up to the RETURN key <LF>. You can use multiple variables to store individual words, the variable store the remainder of the input lines; multiple words and whitespace. • Interrupt handling: trap ‘command’ [signal] - Specify commands to be executed when the shell receives signals {see test). See also kill and nohup commands for further use of signals. • SIGNALS `HUP‘ 1. Hangup. `INT‘ 2. Terminal interrupt. `QUIT‘ 3. Terminal quit. `ABRT‘ 6. Process abort. `KILL‘ 9. Kill (cannot be caught or ignored). `ALRM‘ 14. Alarm Clock. `TERM‘ 15. Termination.

  33. Bourne Special Commands • Command Description ------------------------------------------------------------------------------ • : The null command returns a zero exit value • . file Executes commands specified in file using the search path and not starting a subshell • break [n] Exits the nth iteration from the for, while, or until loop • continue [n] Resumes the nth iteration of the for, while, or until loop • cd [directory] Changes to the specified directory, or to $HOME if none specified • echo [string] Writes string to standard output • eval [list] Executes the commands specified in list • exec [list] Executes the commands in list in place of the current shell • exit [n] Causes the shell to exit with a return code of n • export [name] Marks the specified name for export to the environment of subsequent commands. • pwd Displays the current working directory • read [name ...] Reads one line from standard input and assigns to name • readonly [name...] Marks name to be read-only • return [n] Causes a function to return a value of n • set [flag[argument] Set Flags • shift [n] Shifts the command line arguments to the left n places ($0 is never shifted) • test Expression Evaluates the expression • times Displays the accumulated user and system times for processes running from the shell • trap [command][n] Runs command when the shell receives a signal n • type [name...] For each name specified, indicates how the shell would interpret it as a command • ulimit [flag[var]] Sets or queries process size limits using a specified flag • umask [nnn] Sets the access mode mask to be used with newly created files. • unset [name...] Removes the specified variable, name from the environment • wait [n] Waits for the child process whose process number is n or all if none specified

  34. Job Control • bg - [jobspec ...] Resume each suspended job jobspec in the background, as if it had been started with ‘&’. If jobspec is not supplied, the current job is used. The return status is zero unless it is run when job control is not enabled, or, when run with job control enabled, any jobspec was not found or specifies a job that was started without job control. Also use with Ctrl Z (sleep). Note also use of & for scheduling a background job. • fg [jobspec] Resume the job jobspec in the foreground and make it the current job. If jobspec is not supplied, the current job is used. The return status is that of the command placed into the foreground, or non-zero if run when job control is disabled or, when run with job control enabled, jobspec does not specify a valid job or jobspec specifies a job that was started without job control. • jobs [-lnprs] [jobspec] jobs -x command [arguments] The first form lists the active jobs. The options have the following meanings: • -l List process ids in addition to the normal information. • -n Display information only about jobs that have changed status since the user was last notified of their status. • -p List only the process id of the job's process group leader. • -r Restrict output to running jobs. • -sRestrict output to stopped jobs. • If jobspec is given, output is restricted to information about that job. If jobspec is not supplied, the status of all jobs is listed. • If the -x option is supplied, jobs replaces any jobspec found in command or arguments with the corresponding process group id, and executes command, passing it arguments, returning its exit status.

  35. Job Control • kill kill [-s sigspec] [-n signum] [-sigspec] jobspec or pid kill -l [exit_status] Send a signal specified by sigspec or signum to the process named by job specification jobspec or process id pid. sigspec is either a case-insensitive signal name such as SIGINT (with or without the SIG prefix) or a signal number; signum is a signal number. If sigspec and signum are not present, SIGTERM is used. The -l option lists the signal names. If any arguments are supplied when -l is given, the names of the signals corresponding to the arguments are listed, and the return status is zero. exit_status is a number specifying a signal number or the exit status of a process terminated by a signal. The return status is zero if at least one signal was successfully sent, or non-zero if an error occurs or an invalid option is encountered • Wait [jobspec or pid ...] Wait until the child process specified by each process id pid or job specification jobspec exits and return the exit status of the last command waited for. If a job spec is given, all processes in the job are waited for. If no arguments are given, all currently active child processes are waited for, and the return status is zero. If neither jobspec nor pid specifies an active child process of the shell, the return status is 127. Wait $! # waits for the last process that is sent to the background • When job control is not active, the kill and wait builtins do not accept jobspec arguments. They must be supplied process ids.

  36. Job Control • nohup: Run a command immune to hangups `nohup' runs the given COMMAND with hangup signals ignored, so that the command can continue running in the background after you log out. Syntax: nohup COMMAND [ARG]... If standard output is a terminal, it is redirected so that it is appended to the file `nohup.out'; if that cannot be written to, it is appended to the file `$HOME/nohup.out'. If that cannot be written to the command is not run. disown [-ar] [-h] [jobspec...] Without options, each jobspec is removed from the table of active jobs. If the -h option is given, the job is not removed from the table, but is marked so that SIGHUP is not sent to the job if the shell receives a SIGHUP. If jobspec is not present, and neither the -a nor -r option is supplied, the current job is used. If no jobspec is supplied, the -a option means to remove or mark all jobs; the -r option without a jobspec argument restricts operation to running jobs. • suspend suspend [-f] Suspend the execution of this shell until it receives a SIGCONT signal. A login shell cannot be suspended; the -f option can be used to override this and force the suspension. • crontab – use the systems scheduler to schedule a job • at [timespec] command – schedule a specific job • batch – ‘at’ variant on some systems • trap – builtin command trat redirects processing based on process signal.

  37. Bourne Shell Futures • Korn Shell (ksh) is a combination of C shell and Bourne shell syntax. It is the default shell on certain UNIX’es (Solaris). • Current Bourne shell (4.0) development is under GNU (i.e. LINUX) and is becoming more like Korn and C Shell in capability and syntax. LINUX is leading in BASH development displacing KSH and CSH. • This can cause compatibility issues with bash on older versions of UNIX as USL development has stalled at System V R4.2 due to licensing issues. And makes script portability an issue. Test scripts with sh –vx. • Programming caveats - commands with backwards compatibility issues: - arrays - arithmetic expansion $(()) or [[]] - {} - directory stack commands: dirs, popd, pushd

More Related