Bourne Again Shell Session Linux Command

This chapter is from the book

Shell Basics

This department covers writing and using startup files, redirecting standard error, writing and executing simple beat out scripts, separating and group commands, implementing task command, and manipulating the directory stack.

Startup Files

When a shell starts, it runs startup files to initialize itself. Which files the beat runs depends on whether it is a login beat out, an interactive beat out that is non a login beat (such as you get by giving the command fustigate), or a noninteractive shell (one used to execute a shell script). Y'all must have read access to a startup file to execute the commands in it. Mac OS Ten puts appropriate commands in some of these files. This department covers bash startup files. See page 340 for information on tcsh startup files.

Login Shells

The files covered in this section are executed past login shells and shells that y'all beginning with the ––login choice. Login shells are, by their nature, interactive.

/etc/profile

The vanquish first executes the commands in /etc/contour. By default when called from bash, a command in this file calls /etc/bashrc. Superuser can ready this file to establish systemwide default characteristics for bash users.

.bash_profile .bash_login .profile

Next the shell looks for ~/.bash_profile, ~/.bash_login, and ~/.profile (~/ is shorthand for your home directory), in that order, executing the commands in the starting time of these files it finds. Y'all tin can put commands in one of these files to override the defaults set in /etc/profile.

.bash_logout

When you log out, bash executes commands in the ~/.bash_logout file. Oft commands that make clean upwardly 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 not executed by interactive, nonlogin shells. Even so, these shells inherit from the login shell variables that are prepare by these startup files.

/etc/bashrc

Although not called by bash directly, many ~/.bashrc files phone call /etc/bashrc. This setup allows Superuser to establish systemwide default characteristics for nonlogin bash 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 non executed past noninteractive shells, such every bit those that runs shell scripts. Yet, these shells inherit from the login beat out variables that are ready by these startup files.

BASH_ENV

Noninteractive shells await for the environment variable BASH_ENV (or ENV, if the shell is called as sh) and execute commands in the file named past this variable.

Setting Up Startup Files

Although many startup files and types of shells exist, ordinarily all you need are the .bash_profile and .bashrc files in your home directory. Commands like 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 home directory exists. See page 871 for more than 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 on in this chapter. In any startup file, you must export variables and functions that you want to be available to child processes. For more information refer to "Locality of Variables" on folio 560.

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

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

Side by side is a sample .bashrc file. The first command executes the commands in the /etc/bashrc file if it exists. Side by side the VIMINIT (page 180) variable is fix and exported and several aliases (page 311) are established. The final command defines a role (folio 314) that swaps the names of 2 files.

$          cat ~/.bashrc          if [ -f /etc/bashrc ]; then     source /etc/bashrc             # read global startup file if it exists fi set -o noclobber                   # forestall overwriting files unset MAILCHECK                    # plow off "you have new postal service" notice consign VIMINIT='gear up ai aw'         # set up vim options alias df='df -h'                   # set upwards aliases allonym rm='rm -i'                   # always do interactive rm's alias lt='ls -ltrh | tail' alias h='history | tail' allonym ch='chmod 755 '  function switch()                  # a function to substitution the names {                                  # of two files    local tmp=$$switch    mv "$1" $tmp    mv "$2" "$ane"    mv $tmp "$ii" }        

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

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

In the following case, .bashrc sets several variables and sets PS1, the prompt, to the proper noun of the host. The . builtin puts the new values into effect.

$          true cat ~/.bashrc          export TERM=vt100             # set the concluding type export PS1="$(hostname -f): " # set the prompt string export CDPATH=:$HOME          # add together Dwelling to CDPATH string stty kill '^u'                # set up kill line to command-u $          . ~/.bashrc          bravo.instance.com:        

Commands That Are Symbols

The Bourne Again Crush uses the symbols (, ), [, ], and $ in a diverseness of means. To minimize defoliation, Table eight-1 lists the most mutual use of each of these symbols, even though some of them are non introduced until afterward.

Table 8-1. Builtin commands that are symbols

Symbol

Command

( )

Subshell (page 271)

$( )

Command substitution (page 327)

(( ))

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

$(( ))

Arithmetics expansion (non for use with an enclosed equal sign) (page 325)

[ ]

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

[[ ]]

Conditional expression; similar to [ ] simply adds string comparisons (page 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 ship output to standard fault. A command can send error messages to standard mistake to keep them from getting mixed up with the information it sends to standard output.

But every bit it does with standard output, past default the trounce sends a command'southward standard error to the screen. Unless you lot redirect ane or the other, y'all may not know the difference between the output a control sends to standard output and the output it sends to standard error. This section covers the syntax used by the Bourne Once again Beat out. See page 346 if you are using the TC Shell.

File descriptors

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

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

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

When y'all redirect standard output of a control, output sent to standard error is non affected and still appears on the screen.

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

Similarly, when you ship standard output through a pipage, standard error is not affected. The following example sends standard output of cat through a pipe to tr (folio 879), which in this example converts lowercase characters to uppercase. The text that cat sends to standard error is not translated because information technology goes directly to the screen rather than through the piping.

$          true 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 ii> tells the shell where to redirect standard error (file descriptor 2). The 1> tells the shell where to redirect standard output (file descriptor one). You lot tin can utilise > in place of 1>.

$          true cat x y ane> hold1 two> hold2          $          cat hold1          This is y. $          cat hold2          cat: ten: No such file or directory        

Duplicating a file descriptor

In the next instance, 1> redirects standard output to concord. Then 2>&1 declares file descriptor two to exist a duplicate of file descriptor ane. Every bit a result both standard output and standard fault are redirected to hold.

$          cat 10 y i> agree two>&ane          $          cat hold          true cat: x: No such file or directory This is y.        

In the preceding example, 1> concord precedes 2>&1. If they had been listed in the opposite guild, standard error would have been made a duplicate of standard output before standard output was redirected to agree. In that example merely standard output would have been redirected to hold.

The next example declares file descriptor 2 to exist a duplicate of file descriptor ane and sends the output for file descriptor 1 through a piping to the tr command.

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

Sending errors to standard error

You tin also utilise 1>&2 to redirect standard output of a command to standard error. This technique is ofttimes used in beat scripts to send the output of echo to standard mistake. In the following script, standard output of the first echo is redirected to standard mistake:

$          cat message_demo          echo This is an error message. 1>&2 repeat This is non an error message.        

If you redirect standard output of message_demo, fault letters such as the i produced by the kickoff echo will even so become to the screen because y'all have not redirected standard error. Considering standard output of a shell script is frequently redirected to another file, you can use this technique to display on the screen error messages generated by the script. The lnks script (page 532) uses this technique. You can as well use the exec builtin to create additional file descriptors and to redirect standard input, standard output, and standard error of a shell script from within the script (page 574).

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

Table 8-2. Redirection operators

Operator

Significant

< filename

Redirects standard input from filename .

> filename

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

>| filename

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

>> filename

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

<& yard

Duplicates standard input from file descriptor yard (page 555).

[n] >& m

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

[n] <&-

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

[due north] >&-

Closes standard output or file descriptor n if specified.

Writing a Unproblematic Shell Script

A shell script is a file that contains commands that the crush can execute. The commands in a beat script can be whatever commands you can enter in response to a shell prompt. For instance, a command in a shell script might run a Mac Os 10 utility, a compiled program, or another shell script. Similar the commands you give on the control line, a command in a shell script tin can utilise cryptic file references and can take its input or output redirected from or to a file or sent through a pipe (page 128). You tin can also apply pipes and redirection with the input and output of the script itself.

In improver to the commands you would ordinarily use on the command line, command flow commands (also called command structures) find near of their use in shell scripts. This group of commands enables you to alter the order of execution of commands in a script but as you would alter the society of execution of statements using a structured programming linguistic communication. 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 some other. Thus a trounce script enables yous to simply and quickly initiate a complex series of tasks or a repetitive procedure.

chmod: Makes a File Executable

To execute a trounce script past giving its name equally a control, you must have permission to read and execute the file that contains the script (refer to "Admission Permissions" on page 87). Read permission enables you to read the file that holds the script. Execute permission tells the shell and the system that the owner, group, and/or public has permission to execute the file; information technology implies that the content of the file is executable.

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

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

You cannot execute whoson by giving its proper noun as a command because you do non have execute permission for the file. The crush does not recognize whoson as an executable file and issues an error message when you endeavor to execute information technology. When y'all give the filename equally an argument to fustigate (fustigate whoson), fustigate takes the argument to be a shell script and executes information technology. In this case bash is executable and whoson is an argument that bash executes so you do not need to have permission to execute whoson. You can do the aforementioned with tcsh script files.

The chmod utility changes the admission privileges associated with a file. Effigy 8-one shows ls with the -l option displaying the admission privileges of whoson before and after chmod gives execute permission to the file'southward possessor.

08fig01.gif

Figure eight-one Using chmod to make a shell script executable

The first ls displays a hyphen (-) equally the fourth character, indicating that the owner does not have permission to execute the file. Next chmod gives the owner execute permission: The u+x causes chmod to add (+) execute permission (x) for the owner (u). (The u stands for user, although it means the owner of the file who may be the user of the file at any given time.) The second argument is the name of the file. The 2d ls shows an ten in the fourth position, indicating that the owner at present has execute permission.

If other users will execute the file, you must also change group and/or public access permissions for the file. Any user must have execute access to employ the file's name as a control. If the file is a vanquish script, the user trying to execute the file must too accept read access to the file. Y'all do not need read access to execute a binary executable (compiled program).

The final control in Figure 8-1 shows the crush executing the file when its name is given every bit a command. For more than information refer to "Access Permissions" on page 87 and to ls and chmod in Part V.

#! Specifies a Crush

Yous 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 organization checks the initial characters of a program earlier attempting to exec information technology, these characters save the organisation from making an unsuccessful effort. If #! are the first two characters of a script, the organization interprets the characters that follow as the absolute pathname of the utility that should execute the script. This can exist the pathname of whatever plan, non just a beat. The following case specifies that bash should run the script:

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

The #! characters are useful if you have a script that you want to run with a shell other than the beat out yous are running the script from. The following instance shows a script that should be 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 system ensures that tcsh executes the script no thing which vanquish you run it from.

You can use ps -50 within a shell script to brandish the name of the shell that is executing the script. The three lines that ps displays in the following example show the procedure running the parent bash trounce, the procedure running the tcsh script, and the procedure running the ps control:

$          cat tcsh_script2          #!/bin/tcsh ps -l  $          tcsh_script2          UID  PID PPID CPU PRI NI   VSZ  RSS WCHAN STAT TT    TIME COMMAND   501  915  914   0  31  0 27792  828 -     South+   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 do not follow #! with the proper name of an executable program, the crush reports that information technology cannot discover the control that you asked information technology to run. Y'all tin optionally follow #! with Spaces. If yous 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.

Meet page 653 for an instance of a stand-lone sed script that uses #!.

# Begins a Annotate

Comments make shell scripts and all lawmaking easier to read and maintain by you lot and others. The comment syntax is common to both the Bourne Once more and the TC Shells.

If a pound sign (#) in the outset graphic symbol position of the showtime line of a script is non immediately followed by an assertion point (!) or if a pound sign occurs in whatsoever other location in a script, the shell interprets it equally the outset of a comment. The vanquish then ignores everything betwixt the pound sign and the stop of the line (the next NEWLINE graphic symbol).

Running a Beat Script

fork and exec organization calls

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 control. Like fork, the exec routine is executed past the operating system (a system call). If the command is a binary executable program, such as a compiled C program, exec succeeds and the arrangement overlays the newly created subshell with the executable program. If the command is a trounce script, exec fails. When exec fails, the control is assumed to be a shell script, and the subshell runs the commands in the script. Different a login beat, which expects input from the control line, the subshell takes its input from a file: the crush script.

As discussed earlier, if you lot have a vanquish script in a file that yous do not take execute permission for, you can run the commands in the script by using a fustigate command to exec a shell to run the script directly. In the post-obit case, bash creates a new trounce that takes its input from the file named whoson:

$          bash whoson        

Because the bash command expects to read a file containing commands, you lot do non demand execute permission for whoson. (You do need read permission.) Fifty-fifty though bash reads and executes the commands in whoson, standard input, standard output, and standard fault remain continued to the terminal.

Although y'all tin use fustigate to execute a beat out script, this technique causes the script to run more than 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 command line. It is also easier to type the proper name, and this do is consistent with the way other kinds of programs are invoked (so you do not need to know whether you are running a shell script or some other kind of plan). However, if bash is non your interactive shell or if you want to come across how the script runs with different shells, you may desire to run a script equally an statement to fustigate or tcsh.

Separating and Grouping Commands

Whether yous give the shell commands interactively or write a crush script, you must divide commands from ane another. This section, which applies to the Bourne Once more and the TC Shells, reviews the means to divide commands that were covered in Chapter 5 and introduces a few new ones.

; and NEWLINE Separate Commands

The NEWLINE character is a unique command separator considering information technology initiates execution of the control preceding it. You accept seen this throughout this book each fourth dimension you press the RETURN fundamental at the end of a command line.

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

          $ x ; y ; z        

If x, y, and z are commands, the preceding command line yields the aforementioned results as the adjacent three commands. The deviation is that in the next example the shell bug a prompt subsequently each of the commands (x, y, and z) finishes executing, whereas the preceding command line causes the beat to issue a prompt only later on z is complete:

          $ ten $ y $ z        

Whitespace

Although the whitespace effectually the semicolons in the earlier case makes the control line easier to read, it is not necessary. None of the command separators needs to be surrounded past SPACEs or TABs.

\ Continues a Control

When you enter a long command line and the cursor reaches the right side of the screen, you tin use a backslash (\) character to go on the command on the next line. The backslash quotes, or escapes, the NEWLINE graphic symbol that follows it so that the shell does not care for the NEWLINE as a control terminator. Enclosing a backslash inside single quotation marks turns off the ability of a backslash to quote special characters such every bit NEWLINE. Enclosing a backslash within double quotation marks has no upshot on the power of the backslash.

Although y'all tin can interruption a line in the centre of a word (token), it is typically easier to break a line but before or afterwards whitespace.

| and & Split up Commands and Do Something Else

The pipe symbol (|) and the background chore symbol (&) are besides command separators. They do non start execution of a command simply practice 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 trounce to execute the job in the background then you get a prompt immediately and tin proceed working on other tasks.

Each of the post-obit command lines initiates a unmarried job comprising three tasks:

          $ x | y | z $ ls -l | grep tmp | less        

In the first task, the shell redirects standard output of chore x to standard input of chore y and redirects y'southward standard output to z's standard input. Because information technology runs the entire job in the foreground, the beat out does non display a prompt until job z runs to completion: Task z does not finish until task y finishes, and job y does non terminate until task x finishes. In the second job, job 10 is an ls -l command, task y is grep tmp, and task z is the pager less. The shell 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 due east in the background and chore 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 background. You lot get a prompt equally soon as f finishes, which may exist earlier d or e finishes.

Before displaying a prompt for a new control, the shell checks whether any background jobs take completed. For each job that has completed, the beat displays its job number, the give-and-take Done, and the control line that invoked the job; then the shell displays a prompt. When the job numbers are listed, the number of the terminal job started is followed by a + graphic symbol and the chore number of the previous task is followed by a - character. Whatever other jobs listed show a Space graphic symbol. After running the final command, the shell displays the following before issuing a prompt:

[1]- Done          d [2]+ Done          e        

The next command line executes all three tasks as groundwork jobs. You get a vanquish prompt immediately:

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

You lot can utilise pipes to ship the output from one task to the next task and an ampersand (&) to run the entire job equally a background job. Over again the prompt comes back immediately. The shell regards the commands joined by a pipe as being a single task. That is, it treats all pipes as unmarried jobs, no matter how many tasks are continued with the pipe (|) symbol or how circuitous they are. The Bourne Over again Shell shows only one procedure placed in the background:

          $ d e f &          [1] 14295        

The TC Shell shows three processes (all belonging to job 1) placed in the background:

tcsh          $ d | due east | f &          [i] 14302 14304 14306        

Job Control

A job is a command pipeline. You lot run a unproblematic job whenever you give the shell a control. For example, type date on the control line and press RETURN: You have run a job. Y'all can as well create several jobs with multiple commands on a single control line:

          $ notice . -print  | sort | lpr & grep -50 alex /tmp/* > alexfiles &          [one] 18839 [2] 18876        

The portion of the command line up to the get-go & is one job consisting of three processes continued by pipes: find (page 728), sort (page 49), and lpr (page 45). The 2d chore is a single procedure running grep. Both jobs take been put into the groundwork by the abaft & characters, so bash does not wait for them to consummate before displaying a prompt.

Using chore control you tin can move commands from the foreground to the background (and vice versa), stop commands temporarily, and listing all the commands that are running in the groundwork or stopped.

jobs: Lists Jobs

The jobs builtin lists all background jobs. The following sequence demonstrates what happens when y'all give a jobs control. Hither the slumber command runs in the groundwork and creates a groundwork chore that jobs reports on:

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

fg: Brings a Job to the Foreground

The shell assigns job numbers to commands you run in the groundwork (page 270). Several jobs are started in the background in the next example. For each job the shell lists the job number and PID number immediately, merely before it issues a prompt.

          $ vim memo &          [1] 1246          $ engagement &          [ii] 1247 $ Sun Dec 4 xi:44:40 PST 2005 [2]+ Done          date          $ discover /usr -name ace -print > findout &          [2] 1269          $ jobs          [one]- Running        vim memo & [ii]+ Running        find /usr -proper name ace -impress > findout &        

Job numbers, which are discarded when a job is finished, can be reused. When you start or put a job in the background, the shell assigns a job number that is one more than the highest job number in apply.

In the preceding example, the jobs command lists the offset job, vim memo, as job 1. The date command does non appear in the jobs list because it finished before jobs was run. Considering the date command was completed earlier find was run, the find command became chore 2.

To move a background task into the foreground, use the fg builtin followed by the job number. Alternatively, y'all tin can requite a percent sign (%) followed immediately by the task number every bit a command. Either of the following commands moves job ii into the foreground:

          $ fg 2        

or

          $ %two        

Yous can also refer to a chore past following the percent sign with a cord that uniquely identifies the beginning of the command line used to start the job. Instead of the preceding command, you could accept used either fg %find or fg %f because both uniquely place job 2. If you follow the percent sign with a question mark and a cord, the cord can match any part of the command line. In the preceding case, fg %?ace too brings task ii into the foreground.

Often the job you wish to bring into the foreground is the but job 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 lot must outset suspend (temporarily stop) the job by pressing the suspend key (usually CONTROL-Z). Pressing the suspend cardinal immediately suspends the chore in the foreground. Y'all tin can then use the bg builtin to resume execution of the job in the groundwork.

          $ bg        

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

          $ (sleep 5; cat > mytext) &          [i] 1343          $ date          Sun Dec 4 11:58:20 PST 2005 [1]+ Stopped                 ( slumber five; cat >mytext )          $ fg          ( slumber 5; true cat >mytext )          Recall to let the cat out! CONTROL-D $        

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

The crush keeps you informed about changes in the status of a task, notifying you when a groundwork job starts, completes, or is stopped, maybe waiting for input from the terminal. The shell also lets y'all know when a foreground chore is suspended. Because notices about a chore beingness run in the groundwork can disrupt your piece of work, the shell delays displaying these notices until just before it displays a prompt. You tin set up notify (page 320) to make the beat brandish these notices without filibuster.

If you lot try to exit from a crush while jobs are stopped, the trounce problems a warning and does not let you to leave. If you then apply jobs to review the list of jobs or you immediately try to get out the beat once more, the trounce allows you to go out and terminates the stopped jobs. Jobs that are running (not stopped) in the background continue to run. In the post-obit example, find (job 1) continues to run after the second exit terminates the shell, but cat (job ii) is terminated:

          $ observe / -size +100k > $Abode/bigfiles ii>&1 &          [1] 1426          $ cat > mytest &          [2] 1428          $ get out          exit There are stopped jobs.  [two]+ Stopped                 true cat >mytest          $ go out          exit login:        

Manipulating the Directory Stack

Both the Bourne Again and the TC Shells allow you to store a listing of directories you lot are working with, enabling you to move easily among them. This list is referred to as a stack. It is analogous to a stack of dinner plates: Yous typically add plates to and remove plates from the pinnacle of the stack, creating a last-in get-go-out, ( LIFO ) stack.

dirs: Displays the Stack

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

          $ dirs          ~/literature        

The dirs builtin uses a tilde (~) to represent the name of the dwelling directory. The examples in the adjacent several sections assume that you are referring to the directory construction shown in Figure 8-2.

08fig02.gif

Figure 8-ii The directory construction in the examples

pushd: Pushes a Directory on the Stack

To alter directories and at the same time add a new directory to the superlative of the stack, utilise the pushd (push directory) builtin. In addition to changing directories, the pushd builtin displays the contents of the stack. The post-obit example is illustrated in Figure 8-3:

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

When you utilize pushd without an argument, information technology swaps the top two directories on the stack and makes the new top directory (which was the second directory) become the new working directory (Figure 8-4):

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

08fig04.gif

Figure 8-four Using pushd to change working directories

Using pushd in this way, yous tin can easily move dorsum and forth between two directories. You can also use cd - to change to the previous directory, whether or non you have explicitly created a directory stack. To access another directory in the stack, phone call pushd with a numeric argument preceded by a plus sign. The directories in the stack are numbered starting with the summit directory, which is number 0. The post-obit pushd command continues with the previous instance, irresolute the working directory to literature and moving literature to the summit 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, apply the popd (pop directory) builtin. As the following case and Figure 8-v show, popd used without an argument removes the peak directory from the stack and changes the working directory to the new top directory:

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

08fig05.gif

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

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

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

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

badserso2001.blogspot.com

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

0 Response to "Bourne Again Shell Session Linux Command"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel