The Command to Execute the Bourne Again Shell From Your Current Shell

This affiliate is from the volume

Vanquish Basics

This section covers writing and using startup files, redirecting standard error, writing and executing simple shell scripts, separating and grouping commands, implementing job control, and manipulating the directory stack.

Startup Files

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 beat (i used to execute a shell script). Y'all must have read access to a startup file to execute the commands in it. Mac OS X puts appropriate commands in some of these files. This department covers fustigate startup files. Run into folio 340 for information on tcsh startup files.

Login Shells

The files covered in this section are executed by login shells and shells that you lot kickoff with the ––login option. Login shells are, by their nature, interactive.

/etc/profile

The shell offset executes the commands in /etc/contour. By default when called from fustigate, a command in this file calls /etc/bashrc. Superuser tin fix this file to establish systemwide default characteristics for bash users.

.bash_profile .bash_login .contour

Next the shell looks for ~/.bash_profile, ~/.bash_login, and ~/.profile (~/ is shorthand for your dwelling house directory), in that club, executing the commands in the first of these files it finds. Yous can put commands in i of these files to override the defaults fix in /etc/profile.

.bash_logout

When you log out, bash executes commands in the ~/.bash_logout file. Oftentimes commands that make clean up after a session, such as those that remove temporary files, go in this file.

Interactive Nonlogin Shells

The commands in the preceding startup files are non executed by interactive, nonlogin shells. However, these shells inherit from the login shell variables that are ready by these startup files.

/etc/bashrc

Although not called by fustigate directly, many ~/.bashrc files call /etc/bashrc. This setup allows Superuser to found systemwide default characteristics for nonlogin fustigate shells.

.bashrc

An interactive nonlogin shell executes commands in the ~/.bashrc file. Typically a startup file for a login shell, such as .bash_profile, runs this file, then that both login and nonlogin shells benefit from the commands in .bashrc.

Noninteractive Shells

The commands in the previously described startup files are not executed by noninteractive shells, such as those that runs shell scripts. However, these shells inherit from the login beat out variables that are ready by these startup files.

BASH_ENV

Noninteractive shells look for the environs variable BASH_ENV (or ENV, if the shell is called equally sh) and execute commands in the file named by this variable.

Setting Upwardly Startup Files

Although many startup files and types of shells exist, unremarkably all y'all need are the .bash_profile and .bashrc files in your home directory. Commands similar to the following in .bash_profile run commands from .bashrc for login shells (when .bashrc exists). With this setup, the commands in .bashrc are executed by login and nonlogin shells.

if [ -f ~/.bashrc ]; then source ~/.bashrc; fi        

The [ -f ~/.bashrc ] tests whether the file named .bashrc in your dwelling directory exists. See page 871 for more information on test and its synonym [].

Sample .bash_profile and .bashrc files follow. Some of the commands used in these files are non covered until later in this chapter. In whatever startup file, you must export variables and functions that yous want to exist available to child processes. For more data refer to "Locality of Variables" on page 560.

$          cat ~/.bash_profile          if [ -f ~/.bashrc ]; then     source ~/.bashrc          # read local startup file if it exists fi PATH=$PATH:.                  # add the working directory to PATH consign PS1='[\h \W \!]\$ '    # fix prompt        

The first command in the preceding .bash_profile file executes the commands in the user'south .bashrc file if it exists. The adjacent command adds to the PATH variable (page 285). Typically PATH is gear up and exported in /etc/profile so it does not demand to be exported in a user's startup file. The final control sets and exports PS1 (page 286), which controls the user's prompt.

Adjacent is a sample .bashrc file. The first command executes the commands in the /etc/bashrc file if information technology exists. Side by side the VIMINIT (page 180) variable is ready and exported and several aliases (page 311) are established. The terminal command defines a function (page 314) that swaps the names of two files.

$          cat ~/.bashrc          if [ -f /etc/bashrc ]; then     source /etc/bashrc             # read global startup file if it exists fi ready -o noclobber                   # prevent overwriting files unset MAILCHECK                    # turn off "you accept new mail" detect consign VIMINIT='set ai aw'         # set vim options allonym df='df -h'                   # set up aliases alias rm='rm -i'                   # always practise interactive rm's alias lt='ls -ltrh | tail' allonym h='history | tail' alias ch='chmod 755 '  part switch()                  # a function to exchange the names {                                  # of two files    local tmp=$$switch    mv "$1" $tmp    mv "$2" "$1"    mv $tmp "$two" }        

. (Dot) or source: Runs a Startup File in the Current Beat out

Afterward yous edit a startup file such as .bashrc, you do not have to log out and log in again to put the changes into result. You can run the startup file using the . (dot) or source builtin (they are the aforementioned command under bash; just source is bachelor nether tcsh [page 376], and simply the dot builtin is available under ksh). Equally with all other commands, the . must be followed by a SPACE on the control line. Using the . or source builtin is similar to running a vanquish script, except that these commands run the script equally role of the electric current process. Consequently, when you use . or source to run a script, changes you make to variables from inside the script touch the shell that y'all run the script from. Yous can use the . or source control to run any shell script—not but a startup file—but undesirable side effects (such every bit changes in the values of shell variables you rely on) may occur. If yous ran a startup file as a regular vanquish script and did non use the . or source builtin, the variables created in the startup file would remain in effect but in the subshell running the script—not in the shell you ran the script from. For more than data refer to "Locality of Variables" on page 560.

In the post-obit example, .bashrc sets several variables and sets PS1, the prompt, to the name of the host. The . builtin puts the new values into effect.

$          cat ~/.bashrc          export TERM=vt100             # set the terminal type consign PS1="$(hostname -f): " # set up the prompt string export CDPATH=:$HOME          # add HOME to CDPATH string stty kill '^u'                # gear up kill line to control-u $          . ~/.bashrc          bravo.example.com:        

Commands That Are Symbols

The Bourne Again Shell uses the symbols (, ), [, ], and $ in a variety of ways. To minimize confusion, Tabular array 8-1 lists the near common use of each of these symbols, even though some of them are not introduced until later.

Table 8-1. Builtin commands that are symbols

Symbol

Command

( )

Subshell (page 271)

$( )

Command exchange (page 327)

(( ))

Arithmetics evaluation; a synonym for allow (apply when the enclosed value contains an equal sign) (page 585)

$(( ))

Arithmetics expansion (not for utilize with an enclosed equal sign) (page 325)

[ ]

The test control. (pages 525, 527, 540, and 871)

[[ ]]

Conditional expression; similar to [ ] but adds string comparisons (folio 586)

Redirecting Standard Error

Chapter 5 covered the concept of standard output and explained how to redirect standard output of a command. In addition to standard output, commands can send output to standard fault. A control can send error messages to standard error to keep them from getting mixed up with the information it sends to standard output.

But as it does with standard output, by default the shell sends a command's standard error to the screen. Unless you redirect 1 or the other, you lot may not know the divergence betwixt the output a command sends to standard output and the output it sends to standard error. This department covers the syntax used by the Bourne Again Crush. See folio 346 if yous are using the TC Shell.

File descriptors

A file descriptor is the place a program sends its output to and gets its input from. When you execute a program, the procedure running the programme opens three file descriptors: 0 (standard input), 1 (standard output), and ii (standard error). The redirect output symbol (> [page 122]) is autograph for i>, which tells the trounce to redirect standard output. Similarly < (folio 124) is short for 0<, which redirects standard input. The symbols two> redirect standard fault. For more than information refer to "File Descriptors" on folio 555.

The post-obit examples demonstrate how to redirect standard output and standard fault to different files and to the same file. When you run the cat utility with the proper name of a file that does non exist and the name of a file that does be, cat sends an error message to standard error and copies the file that does be to standard output. Unless you redirect them, both messages appear on the screen.

$          cat y          This is y. $          true cat 10          cat: x: No such file or directory  $          true cat x y          cat: x: No such file or directory This is y.        

When you redirect standard output of a control, output sent to standard error is not afflicted and still appears on the screen.

$          cat x y > hold          cat: x: No such file or directory $          cat concur          This is y.        

Similarly, when y'all send standard output through a pipe, standard error is not affected. The post-obit example sends standard output of cat through a pipage to tr (page 879), which in this example converts lowercase characters to uppercase. The text that cat sends to standard error is non translated because it goes direct to the screen rather than through the piping.

$          cat x y | tr "[a-z]" "[A-Z]"          cat: x: No such file or directory THIS IS Y.        

The following example redirects standard output and standard error to different files. The notation 2> tells the shell where to redirect standard fault (file descriptor 2). The 1> tells the shell where to redirect standard output (file descriptor 1). You lot tin employ > in place of 1>.

$          cat x y one> hold1 2> hold2          $          cat hold1          This is y. $          true cat hold2          cat: x: No such file or directory        

Duplicating a file descriptor

In the next case, ane> redirects standard output to concord. So 2>&1 declares file descriptor 2 to be a duplicate of file descriptor 1. As a result both standard output and standard error are redirected to hold.

$          cat x y 1> agree 2>&1          $          true cat hold          cat: x: No such file or directory This is y.        

In the preceding example, 1> hold precedes 2>&one. If they had been listed in the contrary order, standard error would accept been made a duplicate of standard output before standard output was redirected to concur. In that case simply standard output would have been redirected to hold.

The next case declares file descriptor 2 to exist a duplicate of file descriptor 1 and sends the output for file descriptor i through a pipe to the tr control.

$          cat x y 2>&1 | tr "[a-z]" "[A-Z]"          True cat: 10: NO SUCH FILE OR DIRECTORY THIS IS Y.        

Sending errors to standard error

You tin can too employ 1>&2 to redirect standard output of a control to standard error. This technique is often used in shell scripts to ship the output of echo to standard error. In the following script, standard output of the kickoff echo is redirected to standard fault:

$          cat message_demo          repeat This is an error bulletin. 1>&ii echo This is not an fault message.        

If you redirect standard output of message_demo, fault messages such as the one produced by the first repeat will still go to the screen because yous take not redirected standard error. Because standard output of a vanquish script is oft redirected to some other file, you can use this technique to brandish on the screen error messages generated by the script. The lnks script (folio 532) uses this technique. You tin also use the exec builtin to create additional file descriptors and to redirect standard input, standard output, and standard mistake of a shell script from within the script (page 574).

The Bourne Again Beat out supports the redirection operators shown in Table 8-2.

Table eight-2. Redirection operators

Operator

Pregnant

< filename

Redirects standard input from filename .

> filename

Redirects standard output to filename unless filename exists and noclobber (folio 125) is set up. If noclobber is not set, this redirection creates filename if it does not exist.

>| filename

Redirects standard output to filename , even if the file exists and noclobber (page 125) is set.

>> filename

Redirects and appends standard output to filename unless filename exists and noclobber (page 125) is gear up. If noclobber is not set up, this redirection creates filename if it does not exist.

<& m

Duplicates standard input from file descriptor grand (folio 555).

[due north] >& one thousand

Duplicates standard output or file descriptor due north if specified from file descriptor m (page 555).

[north] <&-

Closes standard input or file descriptor n if specified (page 555).

[northward] >&-

Closes standard output or file descriptor n if specified.

Writing a Simple Beat out Script

A shell script is a file that contains commands that the vanquish can execute. The commands in a shell script can be whatever commands you tin enter in response to a shell prompt. For example, a command in a shell script might run a Mac Bone Ten utility, a compiled program, or another shell script. Like the commands y'all give on the command line, a control in a trounce script can use ambiguous file references and tin have its input or output redirected from or to a file or sent through a pipe (page 128). You can also apply pipes and redirection with the input and output of the script itself.

In addition to the commands you would commonly utilise on the command line, control menses commands (also chosen control structures) find most of their employ in shell scripts. This group of commands enables yous to alter the club of execution of commands in a script just equally you would alter the social club of execution of statements using a structured programming language. Refer to "Control Structures" on page 524 (bash) and page 364 (tcsh) for specifics.

The shell interprets and executes the commands in a shell script, one after another. Thus a crush script enables y'all to simply and speedily initiate a circuitous series of tasks or a repetitive process.

chmod: Makes a File Executable

To execute a beat out script past giving its name as a command, you must take permission to read and execute the file that contains the script (refer to "Access Permissions" on page 87). Read permission enables you lot to read the file that holds the script. Execute permission tells the beat and the system that the owner, grouping, and/or public has permission to execute the file; it implies that the content of the file is executable.

When you create a shell script using an editor, the file does not typically have its execute permission set. The following example shows a file named whoson that contains a shell script:

$          cat whoson          engagement echo "Users Currently Logged In" who  $          whoson          bash: ./whoson: Permission denied        

You lot cannot execute whoson by giving its name equally a control considering you practise non take execute permission for the file. The shell does not recognize whoson equally an executable file and issues an error bulletin when you try to execute it. When you lot give the filename as an argument to bash (bash whoson), bash takes the argument to be a shell script and executes it. In this case bash is executable and whoson is an statement that bash executes so you practice not demand to accept permission to execute whoson. You tin do the aforementioned with tcsh script files.

The chmod utility changes the access privileges associated with a file. Figure viii-i shows ls with the -l option displaying the access privileges of whoson before and after chmod gives execute permission to the file's owner.

08fig01.gif

Figure 8-ane Using chmod to make a shell script executable

The first ls displays a hyphen (-) as the fourth grapheme, indicating that the owner does non have permission to execute the file. Next chmod gives the possessor execute permission: The u+x causes chmod to add (+) execute permission (x) for the possessor (u). (The u stands for user, although it ways the owner of the file who may exist the user of the file at any given time.) The second argument is the name of the file. The second ls shows an x in the fourth position, indicating that the owner now has execute permission.

If other users volition execute the file, you must likewise modify group and/or public access permissions for the file. Whatever user must have execute admission to use the file'southward name as a command. If the file is a trounce script, the user trying to execute the file must also take read access to the file. You do not need read access to execute a binary executable (compiled program).

The final control in Figure 8-1 shows the shell executing the file when its name is given as a command. For more information refer to "Access Permissions" on folio 87 and to ls and chmod in Office V.

#! Specifies a Shell

You lot can put a special sequence of characters on the start line of a file to tell the operating system which shell should execute the file. Because the operating system checks the initial characters of a program before attempting to exec it, these characters salvage the system from making an unsuccessful attempt. If #! are the start ii characters of a script, the system interprets the characters that follow equally the absolute pathname of the utility that should execute the script. This tin can be the pathname of any program, not just a vanquish. The following example specifies that bash should run the script:

$          cat bash_script          #!/bin/bash echo "This is a Bourne Once again Shell script."        

The #! characters are useful if y'all have a script that y'all want to run with a trounce other than the vanquish you are running the script from. The following example shows a script that should exist executed by tcsh:

$          cat tcsh_script          #!/bin/tcsh echo "This is a tcsh script." set person = jenny echo "person is $person"        

Because of the #! line, the operating arrangement ensures that tcsh executes the script no matter which crush yous run it from.

You tin can use ps -fifty within a beat script to display the name of the shell that is executing the script. The three lines that ps displays in the following case show the process running the parent bash shell, the process running the tcsh script, and the process running the ps command:

$          cat tcsh_script2          #!/bin/tcsh ps -l  $          tcsh_script2          UID  PID PPID CPU PRI NI   VSZ  RSS WCHAN STAT TT    Fourth dimension COMMAND   501  915  914   0  31  0 27792  828 -     Southward+   p2 0:00.07 -bash   501 2160 2156   0  31  0 27792  808 -     Ss   p4 0:00.02 -bash   501 2165 2160   0  31  0 31816 1148 -     S+   p4 0:00.01 /bin/tc        

If y'all exercise not follow #! with the name of an executable plan, the beat out reports that it cannot find the control that y'all asked it to run. You can optionally follow #! with SPACEs. If y'all omit the #! line and try to run, for example, a tcsh script from bash, the shell may generate error messages or the script may not run properly.

See page 653 for an example of a stand-alone sed script that uses #!.

# Begins a Comment

Comments make shell scripts and all code easier to read and maintain by you and others. The comment syntax is mutual to both the Bourne Once again and the TC Shells.

If a pound sign (#) in the kickoff character position of the start line of a script is not immediately followed past an assertion point (!) or if a pound sign occurs in whatsoever other location in a script, the shell interprets information technology as the offset of a comment. The shell and so ignores everything betwixt the pound sign and the end of the line (the side by side NEWLINE character).

Running a Crush Script

fork and exec system calls

A control on the command line causes the beat to fork a new process, creating a duplicate of the beat out process (a subshell). The new process attempts to exec (execute) the command. Like fork, the exec routine is executed by the operating system (a arrangement call). If the control 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 beat script, and the subshell runs the commands in the script. Unlike a login shell, which expects input from the control line, the subshell takes its input from a file: the trounce script.

Every bit discussed before, if yous take a shell script in a file that y'all do non take execute permission for, you can run the commands in the script by using a bash command to exec a shell to run the script direct. In the following example, bash creates a new shell that takes its input from the file named whoson:

$          bash whoson        

Because the fustigate control expects to read a file containing commands, you lot practise non need execute permission for whoson. (You do demand read permission.) Even though bash reads and executes the commands in whoson, standard input, standard output, and standard mistake remain connected to the terminal.

Although you lot can use bash to execute a shell script, this technique causes the script to run more slowly than giving yourself execute permission and directly invoking the script. Users typically prefer to make the file executable and run the script by typing its proper name on the control line. Information technology is as well easier to blazon the name, and this exercise is consequent with the way other kinds of programs are invoked (so you exercise not need to know whether yous are running a beat script or some other kind of program). However, if bash is non your interactive crush or if you want to see how the script runs with different shells, you may want to run a script as an argument to bash or tcsh.

Separating and Grouping Commands

Whether you give the shell commands interactively or write a shell script, you lot must separate commands from one another. This section, which applies to the Bourne Again and the TC Shells, reviews the ways to split up commands that were covered in Chapter v and introduces a few new ones.

; and NEWLINE Separate Commands

The NEWLINE character is a unique command separator because it initiates execution of the command preceding it. Yous take seen this throughout this book each time you printing the Return key at the end of a control line.

The semicolon (;) is a command separator that does not initiate execution of a command and does not change any aspect of how the control functions. You can execute a series of commands sequentially by entering them on a single command line and separating each from the next with a semicolon (;). Y'all initiate execution of the sequence of commands by pressing RETURN:

          $ x ; y ; z        

If 10, y, and z are commands, the preceding control line yields the same results equally the side by side 3 commands. The difference is that in the next case the shell problems a prompt after each of the commands (10, y, and z) finishes executing, whereas the preceding command line causes the shell to consequence a prompt only later on z is consummate:

          $ ten $ y $ z        

Whitespace

Although the whitespace effectually the semicolons in the earlier example makes the control line easier to read, information technology is not necessary. None of the command separators needs to be surrounded by Spaces or TABs.

\ Continues a Control

When you enter a long command line and the cursor reaches the correct side of the screen, you can use a backslash (\) grapheme to continue the command on the adjacent line. The backslash quotes, or escapes, the NEWLINE character that follows it so that the trounce does not treat the NEWLINE as a command terminator. Enclosing a backslash within single quotation marks turns off the power of a backslash to quote special characters such as NEWLINE. Enclosing a backslash inside double quotation marks has no effect on the ability of the backslash.

Although you can break a line in the middle of a word (token), it is typically easier to break a line but earlier or after whitespace.

| and & Dissever Commands and Practise Something Else

The piping symbol (|) and the groundwork task symbol (&) are also command separators. They practice not start execution of a control but do alter some attribute 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 groundwork and then you get a prompt immediately and can continue working on other tasks.

Each of the following control lines initiates a single task comprising iii tasks:

          $ 10 | y | z $ ls -50 | grep tmp | less        

In the offset job, the shell redirects standard output of task x to standard input of task y and redirects y's standard output to z's standard input. Because it runs the entire task in the foreground, the shell does not brandish a prompt until job z runs to completion: Task z does not finish until chore y finishes, and chore y does not finish until task x finishes. In the 2d chore, task x is an ls -l command, task y is grep tmp, and task z is the pager less. The beat out displays a long (wide) listing of the files in the working directory that contain the string tmp, piped through less.

The next command line executes tasks d and e in the background and task f in the foreground:

          $ d & e & f          [1] 14271 [2] 14272        

The shell displays the job number between brackets and the PID (process identification) number for each process running in the groundwork. You get a prompt as shortly equally f finishes, which may be earlier d or east finishes.

Before displaying a prompt for a new command, the shell checks whether any background jobs take completed. For each job that has completed, the shell displays its job number, the word Done, and the command line that invoked the job; then the shell displays a prompt. When the chore numbers are listed, the number of the last task started is followed by a + graphic symbol and the task number of the previous task is followed by a - grapheme. Any other jobs listed evidence a Infinite character. Afterward running the last command, the shell displays the following before issuing a prompt:

[i]- Done          d [2]+ Done          east        

The next command line executes all iii tasks as background jobs. You get a shell prompt immediately:

          $ d & e & f &          [1] 14290 [2] 14291 [3] 14292        

Yous tin can use pipes to ship the output from 1 chore to the next task and an ampersand (&) to run the entire job as a background task. Once again the prompt comes back immediately. The shell regards the commands joined past a pipe equally beingness a single job. That is, it treats all pipes as single jobs, no affair how many tasks are continued with the piping (|) symbol or how complex they are. The Bourne Again Trounce shows only one process placed in the background:

          $ d e f &          [1] 14295        

The TC Shell shows 3 processes (all belonging to job i) placed in the groundwork:

tcsh          $ d | e | f &          [1] 14302 14304 14306        

Job Control

A job is a command pipeline. You run a simple job whenever you give the shell a command. For example, type date on the command line and press Return: You have run a job. Yous can also create several jobs with multiple commands on a unmarried control line:

          $ find . -impress  | sort | lpr & grep -l alex /tmp/* > alexfiles &          [i] 18839 [two] 18876        

The portion of the command line up to the first & is one job consisting of three processes connected by pipes: discover (folio 728), sort (page 49), and lpr (page 45). The 2nd job is a single process running grep. Both jobs have been put into the background by the trailing & characters, so bash does not wait for them to complete before displaying a prompt.

Using task control y'all can move commands from the foreground to the background (and vice versa), finish commands temporarily, and list all the commands that are running in the groundwork or stopped.

jobs: Lists Jobs

The jobs builtin lists all groundwork jobs. The following sequence demonstrates what happens when you give a jobs command. Here the slumber command runs in the background and creates a background job that jobs reports on:

          $ sleep 60 &          [1] 7809          $ jobs          [1] + Running                           sleep sixty &        

fg: Brings a Task to the Foreground

The beat out assigns job numbers to commands you run in the background (page 270). Several jobs are started in the groundwork in the adjacent case. For each chore the shell lists the job number and PID number immediately, just before it problems a prompt.

          $ vim memo &          [1] 1246          $ date &          [ii] 1247 $ Lord's day Dec 4 11:44:40 PST 2005 [ii]+ Done          date          $ observe /usr -proper name ace -print > findout &          [2] 1269          $ jobs          [1]- Running        vim memo & [2]+ Running        find /usr -name ace -print > findout &        

Task numbers, which are discarded when a chore is finished, can be reused. When you get-go or put a job in the groundwork, the shell assigns a job number that is one more than than the highest job number in use.

In the preceding example, the jobs command lists the starting time job, vim memo, as task 1. The date command does not announced in the jobs listing because it finished earlier jobs was run. Considering the appointment command was completed earlier notice was run, the discover command became job 2.

To move a background task into the foreground, utilise the fg builtin followed by the chore number. Alternatively, you lot can give a percentage sign (%) followed immediately by the job number equally a command. Either of the following commands moves job two into the foreground:

          $ fg two        

or

          $ %2        

You can also refer to a job by post-obit the pct sign with a string that uniquely identifies the starting time of the command line used to start the task. Instead of the preceding command, you could take used either fg %observe or fg %f because both uniquely identify task 2. If you follow the per centum sign with a question mark and a string, the string can lucifer any office of the command line. In the preceding example, fg %?ace also brings task 2 into the foreground.

Often the job you wish to bring into the foreground is the but task running in the background or is the job that jobs lists with a plus (+). In these cases you can use fg without an argument.

bg: Sends a Job to the Background

To move the foreground job to the background, you must first append (temporarily stop) the job past pressing the suspend key (ordinarily Command-Z). Pressing the suspend key immediately suspends the job in the foreground. You can then employ the bg builtin to resume execution of the job in the background.

          $ bg        

If a background chore attempts to read from the terminal, the shell stops it and notifies you that the task has been stopped and is waiting for input. You must then move the job into the foreground so that it can read from the terminal. The shell displays the command line when it moves the job into the foreground.

          $ (sleep v; cat > mytext) &          [1] 1343          $ date          Sun Dec 4 11:58:20 PST 2005 [ane]+ Stopped                 ( sleep v; true cat >mytext )          $ fg          ( sleep 5; cat >mytext )          Remember to allow the true cat out! Control-D $        

In the preceding example, the shell displays the task number and PID number of the background job as shortly as it starts, followed by a prompt. Demonstrating that you can requite a command at this betoken, the user gives the control date and its output appears on the screen. The vanquish waits until only before it issues a prompt (subsequently appointment has finished) to notify you that job one is stopped. When yous give an fg command, the trounce puts the task in the foreground and you lot tin enter the input that the control is waiting for. In this case the input needs to be terminated with a CONTROL-D to signify EOF (stop of file). The vanquish then displays some other prompt.

The shell keeps you informed almost changes in the condition of a job, notifying you lot when a background job starts, completes, or is stopped, perhaps waiting for input from the final. The shell too lets you know when a foreground job is suspended. Because notices about a job being run in the groundwork can disrupt your work, the vanquish delays displaying these notices until but before information technology displays a prompt. You tin can set notify (page 320) to make the beat display these notices without delay.

If you lot try to exit from a shell while jobs are stopped, the vanquish issues a alert and does not allow you to go out. If you then use jobs to review the list of jobs or you lot immediately try to get out the vanquish once again, the shell allows you to exit and terminates the stopped jobs. Jobs that are running (not stopped) in the background proceed to run. In the following example, find (job one) continues to run subsequently the second go out terminates the shell, just true cat (job ii) is terminated:

          $ find / -size +100k > $HOME/bigfiles 2>&ane &          [1] 1426          $ cat > mytest &          [2] 1428          $ exit          exit At that place are stopped jobs.  [two]+ Stopped                 cat >mytest          $ leave          leave login:        

Manipulating the Directory Stack

Both the Bourne Again and the TC Shells allow you to shop a list of directories you are working with, enabling you to motion easily amid them. This list is referred to as a stack. It is coordinating to a stack of dinner plates: You typically add plates to and remove plates from the top of the stack, creating a last-in offset-out, ( LIFO ) stack.

dirs: Displays the Stack

The dirs builtin displays the contents of the directory stack. If you phone call dirs when the directory stack is empty, information technology displays the name of the working directory:

          $ dirs          ~/literature        

The dirs builtin uses a tilde (~) to correspond the proper noun of the home directory. The examples in the next several sections assume that you are referring to the directory structure shown in Figure 8-2.

08fig02.gif

Figure 8-2 The directory structure in the examples

pushd: Pushes a Directory on the Stack

To change directories and at the aforementioned time add a new directory to the acme of the stack, use the pushd (push directory) builtin. In addition to changing directories, the pushd builtin displays the contents of the stack. The following instance is illustrated in Figure viii-3:

          $ pushd ../demo          ~/demo ~/literature          $ pwd          /Users/sam/demo          $ pushd ../names          ~/names ~/demo ~/literature          $ pwd          /Users/sam/names        

When y'all utilise pushd without an argument, it swaps the pinnacle 2 directories on the stack and makes the new top directory (which was the second directory) become the new working directory (Effigy eight-iv):

          $ pushd          ~/demo ~/names ~/literature          $ pwd          /Users/sam/demo        

08fig04.gif

Figure 8-4 Using pushd to change working directories

Using pushd in this way, you can easily movement back and along between 2 directories. You can besides utilise cd - to change to the previous directory, whether or not you lot take explicitly created a directory stack. To access another directory in the stack, call pushd with a numeric argument preceded by a plus sign. The directories in the stack are numbered starting with the top directory, which is number 0. The following pushd command continues with the previous instance, changing the working directory to literature and moving literature to the pinnacle of the stack:

          $ pushd +2          ~/literature ~/demo ~/names          $ pwd          /Users/sam/literature        

popd: Pops a Directory Off the Stack

To remove a directory from the stack, use the popd (pop directory) builtin. As the following example and Figure eight-5 prove, popd used without an argument removes the top directory from the stack and changes the working directory to the new superlative directory:

          $ dirs          ~/literature ~/demo ~/names          $ popd          ~/demo ~/names          $ pwd          /Users/sam/demo        

08fig05.gif

Figure eight-5 Using popd to remove a directory from the stack

To remove a directory other than the summit one from the stack, use popd with a numeric argument preceded by a plus sign. The following instance removes directory number 1, demo:

          $ dirs          ~/literature ~/demo ~/names          $ popd +1          ~/literature ~/names        

Removing a directory other than directory number 0 does not change the working directory.

loftusnessittere.blogspot.com

Source: https://www.informit.com/articles/article.aspx?p=441605&seqNum=2

0 Response to "The Command to Execute the Bourne Again Shell From Your Current Shell"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel