See the world from the eyes of the shell

Source: Internet
Author: User
Tags arithmetic arithmetic operators echo command integer division parent directory

In this chapter we is going to look at some of the ' magic ' that occurs on the command line when you press the Enter KEY.W Hile we'll examine several interesting and complex features of the shell,we would do it with just one new command:

    • Echo-display a line of text

(character) expand

Each time, type a command line and press the Enter Key,bash performs several processes upon (based on) the text before it Carr IES out your command. We have seen a couple of cases of what a simple character sequence,for example "*", can has a lot of meaning of the She LL. (We've seen a couple of examples: a simple sequence of characters, "*", how rich the meaning of the shell is), the process of that makes this happen is called expansion. With expansion,you type something and it's expanded into something else before the shell acts upon it. To demonstrate (description, demo, proof) What we mean by This,let's take a look at the Echo Command.echo was a shell builtin that performs A very simple task. It prints out their text arguments on standard output:

That's pretty straightforward (upright, candid, honest, simple, understandable). Any argument passed to echo gets displayed. Let ' s try another example:

So what just happened? Why didn ' t echo print "*"? As you recall (recall, recall) from our work with wildcards, the "*" character means match any characters in a filename,but what we Didn ' t see in our origianal discussion is how the shell does that. The simple answer are that the shell expands the "*" to something else (in this instance,the names of the files in the cur Rent working directory) before the echo command is executed. When the ENTER key was pressed,the shell automatically expands any qualifying (make qualified, eligible) characters on the command line Before the command is carried out,so the echo command never saw the "*" and only its expanded result. Knowing this and we can see that echo behaved as expected.

Pathname expansion

The mechanism (construction, mechanism) by which wildcards works is called pathname expansion. (The working mechanism on which wildcards depend is called path name expansion) If We try some of the techniques that we employed in our earlier chapters,we would see that they is really expansions. Given a home directory that's looks like this:

We could carry out the following expansions:

And:

or even:

And looking beyond our home directory:

Pathname Expansion of Hidden Files

As we know,filenames that begin with a period character is hidden. Pathname expansion also respects this behavior. An expansion such as:

echo*

Does not reveal hidden files.

It might appear at first glance so we could include hidden files in an expansion by starting the pattern with a leading Period,like this:

Echo. *

It almost works. However,if we examine the results closely,we would see that the names "." and "..." would also appear in the results. Since These names refer to the current working directory and their parent directory,using this pattern would likely produce a n Incorrect result. We can see this if we try the command:

ls-d.* | Less

To correctly perform pathname expansion The This situation,we has to employ a more specific pattern. This would work correctly:

Ls-d. [!.]? *

This pattern expands to every filename that begins with a period,does does include a second period,contains at least one Additional character and can is followed by any other characters. This would work correctly with the most hidden files (though it still won ' t include filenames with multiple leading periods). The LS command with THE-A option ("Almost all") would provide A correct listing of hidden files;

Ls-a

Wave line expansion (wavy lines unfold)

As recall from our introduction to the CD Command,the tilde (wave character) character ("~") has a special meaning. When used in the beginning of a word,it expands into the name of the home directory of the the name User,or if no user is name D,the Home directory of the current user:

If user "Darui" has an account,then:

Arithmetic expression expansion

The shell allow arithmetic to being performed by expansion. This allow us to use the shell prompt as a calculator:

Arithmetic expansion uses the form:

$ ((expression))

Where expression is an arithmetic expression consisting of values and arithmetic operators.

Arithmetic expansion only supports integers (whole numbers,no decimals (fractional)), but can perform quite a number of different ope Rations. Here is a few of the supported operators:

Table 8-1:arithmetic Operators

Operator Description
+ Addtion
- Subtraction
* Multiplication
/ Division (But remember,since expansion only supports integer arithmetic,results is integers.)
%

Modulo,which simply means, "remainder".

** Exponentiation (Take Power)

Spaces is not significant in arithmetic expressions and expressions is nested (nested). For example,to multiply five squared by three:

Single parenthses is used to group multiple subexpressions. With this technique,we can rewrite the example above and get the same result using a single expansion instead of:

Here's an example using the Division and remainder (residue) operator. Notice the effect of the integer division:

Arithmetic expansion is covered in greater detail in Chapter 35.

Brace expansion (curly brace expansion)

Perhaps the strangest expansion is called brace expansion. With It,you can create multiple the text strings from a pattern containning braces. Here's an example:

Patterns to being brace expanded may contain a leading portion (part) called a preamble (preamble, Telegraph header) and a trailing portion called a PostScript. (PS) The brace expression itself may contain either a comma-separated (comma delimited) List of strings,or a range of Integ ERs or single characters. The pattern may not be contain embeded (implanted, included) whitespace. Here's an example using a range of integers:

A range of letters in reverse order:

Brace expansions may nested:

So what's this good for? The most common application are to do lists of files or directories to be created. For Example,if we were photographers and had a large photo collection of images The We wanted to organize into years and Months,the first thing we might do are create a series of directories named in numeric "Year-month" format. This way,the directory names would sort in chronological (ordered in chronological order). We could type out a complete list of directories,but that's a lot of work and it's Error-prone (error-prone) too. Instead,we could do this:

Pretty slick! (Smooth and effective, effortless)

Command expansion

We ' re only going to touch briefly on parameter expansion in this chapter,but we'll be covering it extensively (broadly) later.i T ' s a feature that's more useful in shell scripts than directly on the command line. Many of its capabilities (capable of doing something) has to does with the system's ability to store small chunks of data and to give each C Hunk a name. Many such chunks,more properly called Variables,are available for your examination. For example,the variable named "user" contains your user name. To invoke parameter expansion and reveal the contents of the USER you would does this:

To see a list of available variables,try this:

You may have noticed, and other types of expansion,if, you mistype a pattern,the expansion would not take place and the echo command would simply display the mistyped pattern. With parameter expansion,if misspell the name of a variable,the expansion would still take place,but would result in an Empty string:

Command substitution (replace)

Command substitution allows us to use the output of a command as an expansion:

One of my favorites goes something like this:

Here we passed the results of which CP as a argument to the LS Command,thereby (therefore) getting the listing of the CP program Without has to know its full pathname. We is not a limited to just simple commands. Entire pipelines can is used (only partial (limited, partial) output shown):

In this example,the results of the pipeline became the argument list of the file command.

There is an alternate (substituted, here Another) syntax for command substitution in older shell programs which is also supported in bash. It uses back-quotes (inverted quotes) instead of the dollar sign and parentheses (parenthesis):

Quote (citation)

Now, we ' ve seen how many ways the shell can perform Expansions,it's time to learn how we can control it. Take for example:

Or

The first example,word-splitting by the shell removed extra whitespace from the echo command ' s list of arguments. In the second Example,parameter expansion substituted a empty string for the value of "$" because it is an undefined var Iable. The shell provides a mechanism called quoting to selectively suppress unwanted expansions. (The shell provides a call-to-invoke mechanism to selectively suppress unwanted expansion)

Double Quote

The first type of quoting we'll look at is double quotes. If you place text inside double Quotes,all the special characters used by the shell lose their special meaning and is Tre Ated as ordinary characters. The exceptions (Exception) $,\ (backslash), and ' (Back-quote). This means, that word-splitting,pathname Expansion,tilde (wavy line) Expansion,and brace (curly braces) expansion is suppressed,but Parameter expansion,arithmetic expansion,and command substitution is still carried out. Using double quotes,we can cope with filenames containing embedded spaces. Say We were the unfortunate victim of a file called both words.txt. If we tried to use this on the command line,word-splitting would cause this to be treated as the separate arguments rather than the desired single argument;

By using the double quotes,we stop the word-splitting and get the desired result;further,we can even repair the damage:

there! Now we don ' t has to keep typing those pesky double quotes.

Remember,parameter expansion,arithmetic expansion,and Command substitution still take place within double quotes:

We should take a moment to look at the effect for double quotes on command substitution. First let's look a little deeper in how word splitting works. In we earlier Example,we saw how word-splitting appears to remove extra spaces in our text:

by Default,word-splitting looks for the presence (presence) of Spaces,tabs,and newlines (linefeed characters) and treats them As delimiters (delimiter) between words. This means, unquoted spaces,tabs,and newlines is not considered to being part of the text. They only serve as separators. (By default, the word segmentation mechanism looks for spaces, tabs, and line breaks in words, and sees them as a qualifier between monotony.) This means that no reference spaces, tabs and line breaks are part of the text, and they are used only as delimiters)Since They separate the words into different arguments,our example command l INE contains a command followed by four distinct arguments. If we add double quotes:

Word-splitting is suppressed and the embedded spaces be not treated as delimiters,rather they become part of the argument . Once The double quotes is added,our command line contains a command followed by a single argument. (??????????? Do not understand the meaning of this sentence)

The fact that newlines is considered delimiters by the word-splitting mechanism causes an Interesting,albeit SUBTLE,EFFEC T on command substitution. Consider the following:

The substitution of a command that is not referenced in the first example causes the command line to contain 38 arguments, because the word segmentation mechanism, the result of a CAL that contains spaces and newline characters, is treated as a delimiter. In two examples, the command line has only one parameter, with embedded spaces and line breaks included in the parameters.

Single quotes

If we need to suppress all expansions,we use a single quotes. Here is a comparison (compare) of unquoted,double Quotes,and single quotes;

As we can see,with each succeeding level of quoting,more and more of the the expansions is suppressed.

Escape character (escape character)

Sometimes we only want to quote a and a single character. To do this,we can precede (before that, before) a character with a Backslash,which in this context is called the escape character. Often This is do inside double quotes to selectively prevent an expansion:

It is also common to use escaping to eliminate the special meaning of a character in a filename. For example,it are possible to use characters in filenames that normally has special meaning to the shell. These would include "$", "!", "&", "", and others. To include a special character in a filename can to this:

To allow a backslash character to appear,escape it by typing "\". Note that within a quotes,the backslash loses its special meaning and was treated as an ordinary character.

Can be useless to a single quote called escape character, the use of a single quote called Blackslash, haha

Backslash Escape Sequences

In addition to its role as the escape character,the backslash was also used as part of a notation to represent certain spec ial characters called control codes. The first thirty-two characters in the ASCII coding scheme is used to transmit commands to teletype-like devices. Some of these codes is familiar (Tab,backspace,linefeed,and carriage retrun), while others is not (null, End-of-transmission,and Acknowlege)

Escape Sequence Meaning
\a Bell ("Alert"-causes the computer to beep)
\b Backspace
\ n Newline.on Unix-like Systems,this produces a linefeed
\ r Carriage return BACKSPACE
\ t Tab

The table above lists some of the common backslash escape sequences. The idea behind this representation using the backslash originated in the C programming language and have been adopted by M Any others,including the shell.

Adding the '-e ' option to echo would enable interpretaion (interpretation) of the escape sequences. Also place them inside $ '. Here,using The Sleep command,a single program that just waits for the specified number of seconds and then Exits,we can CR Eate a primitive countdown timer:

!!!! We need to add the-e option when using these escape character sequences.

Sleep 10;echo-e "Time ' s up \a"

We could also do this:

Sleep 10;echo "Time ' s Up" $ ' \a '

Sum-up

As we move forward with using the shell,we would find that expansions and quoting would be used with increasing frequency (frequency ), so it makes sense to get a good understanding of the They works. In Fact,it could is argued that they is the most important subjects to learn about the shell. Without a proper understanding of expansion,the shell would always be a source of mystery and confusion,and much of it pote Ntial Power wasted.

See the world from the eyes of the shell

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.