game.zxqp58205.com:www.hn7878.com

&Change& SHELL &BASH& 13 Q
Why is called
What is the introduction before the shell
Let us re-examine the relationship between user and computer system
We know that the operation can not leave the computer hardware, but the user can not be driven directly to the hardware
Hardware can only through a drive called the &operating system
(Operating System)"
Software to control ,
In fact, we are talking about every day
Strictly speaking, only one operating system, which we call
(kernel)".
However, from the user's point of view
There is no way to directly manipulate the user
But through the kernel of
Shell &program
Also known as shell, come with
Communication
This is exactly the kernel with
Relationship between the image name. Figure
From a technical point of view, shell is the interaction of a user interface with the system
(interface),
Is designed to allow users to use the command line
(command line)
To use the system to complete the work
Therefore, shell is the most simple definition
Command interpreter
(Command Interpreter):
Translation of the user's commands to the core processing
Meanwhile, the results will translate to the user core
Every time we complete the system log
We made an interactive mode to shell, also known as
login shell
primary shell.
From a trip
Point of view, we
The order issued, are
Child process generated. This is like
We may temporarily call
If the script
(shell script)
Then the command script is a non-interactive mode by another child
shell (sub shell)
To perform
Primary shell is produced
Trip, sub shell and then generate
Schedule of all the commands
On the journey, we have the opportunity to add future
Here, we must know
And the shell is different from the two sets of software
And are to be replaced
Different operating systems use different
And on the same kernel
You can also use different
The default system in linux
Usually can be found in several different shell, and usually will be listed in the following archives
/etc/shells
Different functions have different shell
And also different to each other. Or that
Common shell is divided into two main
burne shell (sh)
burne again shell (bash)
c shell (csh)
tc shell (tcsh)
korn shell (ksh)
Most of the default Linux system
Are the bash, along the following two reasons
Free Software
Gnu project is one of the most successful products
Since its launch loved by the majority of Unix users
Many organizations and is becoming the system standard
------------------
2) shell prompt(PS1)
Carriage Return(CR)
Relationship
When you have successfully logged into a text interface, the majority of cases
You will see a screen flashing the box or the bottom line
Not depending on version
*(coursor).
The role of the cursor is to tell you what your keyboard's keys from the location of the inserted
If a key input and cursor Pianxiang every move the right side of a grid, if the continuous input is too much
Enter the next line is automatically connected
If you have just completed has not entered any registry keys before you see the cursor to the left part of the same line
*(prompt).
The format of the prompt or from different systems have different versions, in the
, Simply note that the closest a visible cursor prompt
Usually follows one of two
To the general user account to use
Administrator
Account Use
In fact, shell prompt message was simple
Is tell the user shell
You can now enter the command line
We can say that the user only with the
shell prompt
To hit the command line
The cursor is a direct keyboard input on the command line the location of the
Enter a key for each user, cursor to move one back
Until he came to read into the command line
CR(Carriage Return,
Generated by the Enter key
Characters so far
The meaning is very simple
Tell the user
My buddy you can run a command line
Strictly speaking
The so-called command-line, that is,
shell prompt
CR characters with the text entered
Why are we here and not say stick with the CR character
Key? The answer revealed in a later study
Acceptable to different commands have different command-line format, or, under normal circumstances
A standard command line format is listed below
command-name options argument
If the view from the technical details, shell will be based on
IFS(Internal Field Seperator)
Entered the command line as the text to the dismantling
And then for the special characters
Be handled first, and finally the whole line re-
command line .
Be sure to understand the meaning of two sentences, we learn in the future will always think back here
IFS is one of
The default field delimiter used, can be composed of one and more of the following buttons
(White Space)
System accepts the command name
(command-name)
Can be obtained from the following channels
A clear path to the external command specified by
Command alias
Custom Function
(function)
Built-in command
(built-in)
Under the external command
Are required for each command line with the command name, which is indispensable
--------------------
Others echo. You
Know asked the echo
Described in the previous chapter to undertake the command line, here we use
And further description of this command
--- Standard study
command line
Consists of three parts
* command_name option argument
Is a very simple. Direct
Will be sent to standard output argument
Usually is in the monitor
The output
We have the opportunity to explain the future, or may first refer to the following discussion
http://www.chinaunix.net/forum/viewtopic.php?t=191375 )
In order to better understand, let us start and what better
Good command
You will find only a blank line, then back to
shell prompt
This is because the echo in the default
End of argument in the display after
Will send a line feed
(new-line charactor).
However, any of the above command did not
argument ,
That result has left a line feed
If you want to cancel this line break can be used to
-n option :
Let us come back to the concept of command line discussion on the case
Good command
* command line
command_name(echo)
option(-n),
There is no
argument .
To see the echo
argument ,
It is not easy! Next, you can try the following input
$ echo first line
first line
$ echo -n first line
first line $
Echo command in the last two
You will find some argument in your screen display
The line breaks, as the-n option is the availability of the other
Obviously, the second
Since newline is canceled, the next
shell prompt
Connected to the output on the same line
In fact, echo addition
-n options
, The commonly used options as well
Enable the conversion backslash control characters
Refer to the table
Close backslash character conversion control
Default case
Cancellation line at the end of the line feed
With the-e option under the
Characters agree
Echo command on the control characters supported by the following table backslash
\a:ALERT / BELL (
Send ringtones from the system speaker
\b:BACKSPACE ,
Delete key is to the left
Cancellation line at the end of the line feed
\E:ESCAPE,
Escape key
\f:FORMFEED,
Feed character
\n:NEWLINE,
Newline characters
\r:RETURN,
Jump bond form
\v:VERTICAL TAB,
Vertical jump bond form
Octal code
To x at the beginning as a hexadecimal
Backslash itself
The form data from O'Reilly Press
Learning the Bash Shell, 2nd Ed.)
Maybe we can learn through examples
Options and control characters
Example One
$ echo -e "a\tb\tc\nd\te\tf"
Use the example
To separate the abc there
Will def change to the next line
Example Two
$ echo -e "\141\011\142\011\143\012\144\011\145\011\146"
As a result with the case, just use
Octal code
Example Three
$ echo -e "\x61\x09\x62\x09\x63\x0a\x64\x09\x65\x09\x66"
And two similar cases, but the switch to
Hexadecimal code
Four patients
$ echo -ne "a\tb\tc\nd\te\bf\a"
Because the letter e followed by the delete key
Therefore, the output is no e
In the end you hear a bell to, it is
Masterpiece!
As the same time using the-n option
So shell prompt immediately after the second line
If you do not have the words-n
Plus a post-
The effect is the same
In fact, in the future
Operation and design of shell script
Command is one of the most frequently used commands
For example, with
To check variable values
On the concept of variables, we left before the next two chapters, we note with
Well, more about
command line
Format, and
Command options
You practice more on their own. Use of
-----------------
Single quote
Where poor
Or come back to our command line
After the first two chapters of the study, should be very clear when you
shell prompt
Behind the keyboard. Until you press
The text you enter is the command line of the
Then the shell will travel to it by way of the implementation of the command you
However, you can also know
You enter each command line in a text
Of the shell is
Category points are then
I can not say that this is precisely the definition proposed, a note
),command line
Every charactor, divided into the following two
* literal:
That is, ordinary text, for
No special features for
Of the shell is
With specific functions of special reserved characters
In dealing on the bash shell
command line
In the order that
Please refer to the O'Reilly Press
Learning the Bash Shell, 2nd Edition,
Section 177 - 180 pages of instructions
Especially the flow chart on page 178
Figure 7-1 ... )
Nothing to talk about, where the lift
abcd.123456
These &words
literal ... (easy?)
However, it often makes us confused meta
..... (confused?)
In fact, the first two chapters we
command line
Two machines have been hit almost every time encounter
One of the three components
Is used to disassemble each word command line
Use, because
shell command line
Is handled by the word
The CR is used to terminate
command line
Used, which is why we knock
The reasons for the command will run
In addition to IFS and
There are commonly used in meta
Set variable
Substitution for variables or operations
Please do not confuse this with the shell prompt
Command line
Redirect file descriptor, or the implementation of the command placed in background
Command will be placed inside the implementation of nested subshell
Or for the operation or command substitution
Will be placed inside the command to execute non-named function
Or the definition of the scope of the variable substitution
The end of the previous command, and ignore the return value
Continue to the next command
The end of the previous command, if the return value
Continue to the next command
The end of the previous command, if the return value
Continue to the next command
Implementation of the command history list
Command line if we need to retain the character of these functions will be turned off if
Addressed the need to quoting
In the bash of
There are three commonly used method of quoting
* hard quote:' ' (
Single quote
Where all the hard quote
Are turned off
* soft quote: " " (
A large proportion of the soft quoe
Will be closed, but some is retained
* escape : \ (
Only immediately
Escape character
Was only closed after a single meta .
Be exempt in the soft quote specific
List, I do not fully know
We need to be added, or through implementation to discover and understand
The following example will help our understanding of quoting
Turn off the space bar is not as
$ C: command not found.
Blank key has been turned off, only as a blank key deal
A variable in the first set when
Not be closed because the space bar, command line will be interpreted as
And then execute the command C
A variable in the second set when
Since the space bar is placed in the soft quote
Was closed and no longer as
* A=B&space&C
In fact, the space bar in terms of
soft quote
Or in hard quote the
Will be closed. Enter key versa
$ echo "$A"
In the above example, because
Which is placed in hard quote
CR character is no longer handled as a
Just a simple line break symbol
(new-line)
Only, because
command line
CR did not have the character
So into the second
shell prompt (PS2,
),command line
And will not end
Until the third line, we entered
Which is not in the hard quote
Therefore, no closed
At this point, command line encounter
Character, thus ending
To the shell to handle
If placed in the words soft quote
Will also be closed
As for the variable when not in soft quote
So when the variable substitution for command line completion and reorganization
Will be interpreted as IFS, and not interpreted as
Similarly, with
CR characters can also be turned off
The above example, the first
With the second
Escape characters are closed
So as not to deal with CR
But the third
Since not been tripped, so as
command line .
However, due to
Key itself in the special shell meta
Trip back, only to cancel
Function, and will not retain their
You may find just a
Bond character arising from it may be possible as these
NL(New Line)
FF(Form Feed)
As for when it will explain why the characters, which I did not go digging out
Party of their own or leave the reader gradually explored
For soft quote with
hard quote
Different, mainly for some
Close or not, to
For illustration
$ echo "$A"
$ echo '$A'
In the first echo command line
Was placed in the soft quote
Will not be closed, so continue to address the variable substitution
Therefore, the echo
Value of the variable output to the screen, will be
In the second echo command line
Was placed in hard quote
Were closed, so
Variable substitution is not used for processing, so the result is
A letter followed by a symbol
--------------------------------------
Practice and Thinking
The following results are different
$ echo '"$A"'
The outermost is the single quotes
$ echo "'$A'"
The outermost is the double quotes
Single quotes and double quotes, in the
Are related in
--------------------------------------
In CU's
Version, I have found many problems for beginners
Understanding with the quoting the relevant
For example, if we
Or call the sed command parameters to set some variables before
Often asked why the issue can not be
To solve these problems, the key point is
And to distinguish shell meta
command meta
We mentioned those meta, are
command line
There are special purpose
For example,
Is to be placed within a series of command line functions in the implementation of anonymous
Can be simply regarded as
command block ),
However, awk is needed
To distinguish the awk command section
(BEGIN, MAIN, END).
If you are so entered in the command line
$ awk {print $0} 1.txt
Did not close the shell,
That shell will be
{print $0}
command block ,
But there is no
Symbol for the command segment, and therefore there
Syntax error in the results
To a solution can be used
hard quote :
$ awk '{print $0}' 1.txt
Hard quote above should be easy to understand
Is to the original
{.&space&.$(
These shell meta off
Avoid being out in the shell in the treatment
And complete as awk parameter
command meta .
Is the awk built-in
field number ,
Awk variable rather than
Its own variables without the use of
If a hard quote to understand the function of
Come to understand soft quote and
It is not difficult
awk "{print \$0}" 1.txt
awk \{print\ \$0\} 1.txt
However, if you want to change
0 value is from another
Variable read into it
For example,
Have variable
The value is 0, then how
command line
Awk in resolved
You can be a direct negation of programs out hard quoe
$ awk '{print $$A}' 1.txt
That is because
In the hard quote is not replaced by the variable
The astute reader
After studying this chapter, I want to
Should be able to explain why we can use the following operation of the bar
awk "{print \$$A}" 1.txt
awk \{print\ \$$A\} 1.txt
awk '{print $'$A'}' 1.txt
awk '{print $'"$A"'}' 1.txt
Wrapped in soft quote in
Perhaps you could give it more options
--------------------------------------
Practice and Thinking
Please use the knowledge learned in this chapter is as follows two strings of the discussion
http://bbs.chinaunix.net/forum/viewtopic.php?t=207178
http://bbs.chinaunix.net/forum/viewtopic.php?t=216729
--------------------------------------
-------------
5) var=value?export
Where differences before and after
Let us temporarily put aside the command line, first to find out
(variable)
The so-called variable, that is, is the use of a specific
Can change to access a &value
In the bash of
You can use the &=& to set or re-define the contents of the variable
name=value
In setting the variable at the right time, must obey the following rules
Both sides can not use the equal sign symbol segmentation
Should also avoid using the reserved characters shell
(meta charactor).
Variable name can not be used
The first letter of variable name can not be a number
Variable name length must not exceed 256 characters
Variable name and variable value of the case is different
(case sensitive).
Here are some common mistakes when setting variables
Can not have
Can not begin with a number
Name can not have
This is with a = b is different
Is acceptable as set
Please refer to the previous section quoting
Does not begin with a number
Available within the variable value
This_Is_A_Long_Name=b
_ Connection can be names or values longer
And case sensitive
Variable substitution
(substitution)*
Were strong, a factor which is that it can at the command line for the replacement of variables
(substitution)
The user can use the command line
Symbols with variable names
In addition to the variable name used outside the definition of = No.
Out of the variable value to the replacement, and then re-form the command line
$ $A -$B $C
The first command line above
Is the shell prompt, not within the command line
It must be emphasized that we replace the variables mentioned
Only in the command line above
Yes, let's go back
command line
Careful analysis of the last line of command line, before being executed is not difficult to find
CR characters in the input before
Symbol will be replaced by processing each of the variables
Replace the variable values from the command line and then re-
Finally, the following command line will be drawn
ls -la /tmp
Remember Chapter I urge you to &be sure to understand
The two lines? If you forget
Then I re-posted here once again
If the view from the technical details, shell will be based on
IFS(Internal Field Seperator)
Entered the command line as the text to the dismantling
And then for the special characters
Be handled first, and finally the whole line re-
command line .
Command line is the most classic
One, that is, for variable substitution!
Shell in the daily operations
We often use the echo command to see the value of a particular variable
For example,
$ echo $A -$B $C
We have learned, echo command only simple to
Sent to &standard output
Our screen is usually
So the above command will get the following result on the screen
ls -la /tmp
This is because the echo command is executed
Will first
$A(ls).$B(la).
To replace the result of the
Using shell variable substitution processing power of
We set the variable to be more flexible
So, B can inherit variable values
Variable &time
The value of the variable
However, not to
Mathematics Luo Ji &to apply the set of variables
For example,
This does not make the variable value into A
Another example
The same will not let the value of B into
Defined above is simply the name of two different variables
And B, their values are
If the variable is redefined, then the original value of the old value will be replaced by the new
This is not exactly &the amount of variable
When we set the variables at the right time, please remember this :
Store a value with a name
This is the only
In addition, we also use the command line variable substitution ability to
Variable value
Thus, the first line we set
Then, the value of the second line and then expanded to
"A:B:C:E" .
Expansion of the above examples, we use the segmentation symbol
To achieve the purpose of expanding
Without segmentation symbol, then there is a problem as
A second time because the value is inherited
The mention for results rather than
Together with E!
To resolve this problem, we can replace the more rigorous treatment
The above example, we use
The scope of the variable name out to the clear definition
In this way, we can
Variable value from BCD to the expansion of the
Variables can in fact do more processing power, these are the variables dealing with a relatively advanced
This stage is not presented, please reference their own
If CU's post
http://www.chinaunix.net/forum/viewtopic.php?t=201843
* export *
Strictly speaking, we are in the current
Defined variables, belong to
Local variables
"(local variable),
Only export orders
Output &deal
Environment variable can be
(environment variable):
$ export A
$ export A=B
Processed through the export output
A variable can become an environment variable for the subsequent command
Right time in the use of export
Please do not forget to shell variables in the command line
Replacement
"(substitution)
For example,
$ export $A
The above command does not output the environment variables A
Instead, for output B
This is because the command line
Will be raised for the first and then B
Back into &for
Parameters
To understand this export, in fact need to
To a thorough understanding of the perspective
The next chapter I will explain to you the concept of process
Please note
Cancel variables
To cancel a variable in the
Unset command can be used to handle
As with the export
Command line, will also be variable substitution
This is actually one of the functions shell
Therefore,
$ unset $A
In fact the cancellation of the variable is not B
In addition, the variable once it has been
After the cancellation, the result is to remove the variable
Not just cancel the variable value
In fact, the following two lines are very different
The first line is set to the variable A
But the second line to the variable A does not exist
Although seen with your eyes, these two variables results in the state in the following command is the same
Please be sure students can identify null value and
The essential difference, which in some advanced variables are very strict on the handling
For example,
$ var=${str=expr}
Definition
$ echo $var
$ echo $str
$ unset str
$ var=${str=expr}
Definition
$ echo $var
$ echo $str
The astute reader
(yes, you!),
A little to think about it
Is not difficult to see why the same should be
var=${str=expr}
In the null and
Difference is under
If you can not tell, it is probably one of the following reasons
You stupid
Do not know
var=${str=expr}
This advanced treatment
Not enough time for digestion and absorption of this shows
I speak good
I do not know, what do you choose
---------------
Where the difference with the source
We CU Shell let this version of the post to talk about it an instance of
( http://www.chinaunix.net/forum/viewtopic.php?t=194191 )
Case, the question is
cd /etc/aa/bb/cc
Can perform
However, when this command to write shell
Does not perform
What is the reason ah
I did not get to the bottom being how to answer, let us look at travel
First, we are running any program
Stroke is the father
(parent process)
Arising out of a child process
(child process),
Child process at the end, it will go back to the parent trip
This is like the Linux system is called
Why drive to fork it
Ah, painting a better understanding of what plans may be
When the child process is generated when there will be some travel from the parent resource allocation
More importantly,
The environment inherited from the parent trip!
Let us return to the previous chapter about the &environment variables
In fact, the so-called environment variables are those variables will be passed to child process
Simple terms, &genetic
Is to distinguish between local variables and environmental variables determining indicators
However, from a genetic point of view
We also find another important feature of the environment variable
Environment variable can only travel from the parent to the child inherited one-way trip. In other words
The environment in the child how to change the itinerary, the trip will not affect the parent environment
Next, let us look at the command script
(shell script)
The concept of
The so-called shell script is simple to say
Is to you usually after the shell prompt enter multi-line
command line
Order to write a file to it
Together with a number of conditions which determine. Interactive interface
Parameters used. Function call
More skills, to make
More &intelligent
The implementation of the
However, if these techniques aside aside, can we really as simple
Just followed the implementation of pre-written command line only
Combined these two concepts
(process + script),
It should not difficult to understand as the meaning of the phrase
Normally, when we execute a
shell script
When, in fact, is to produce a
The child process, and then
Go to the child process command line generated
What, then, that the beginning of this chapter, let us return to the example mentioned new thinking again
cd /etc/aa/bb/cc
Can perform
However, when this command to write shell
Does not perform
What is the reason ah
I had the answer is this
Because, in general we run
shell script
Is subshell to execute
From the process point of view the concept of
Is the parent process to produce a
child process
To perform
When the child after
Will return to parent, but
Environment will not change because of changes in child's
Many of the so-called metadata environment, where the lift
effective id, variable, workding dir
workding dir ($PWD)
The question is where the landlord
When using subshell to run
Then, sub shell of
Cd to change because
But when you return to primary shell
Will not change
To understand the cause of the problem and the principle is good, but
How to solve the problem is probably more interested in us! Right
Well, the next
Let us look good source command
When you have a fork, after the concept of
Is not difficult to understand the source
Source is the so-called
Implemented within the current shell
Rather than produce a sub-shell to execute
Since the implementation of the results were all completed within the current shell
If the script has changed the environment
Of course, will change the current environment it!
Therefore, if we want to separate the original input
Command-line parameters into the command source
Precedent that can easily solve the problem
For example, the implementation of which we are so
./my.script
Now you can change this
source ./my.script
. ./my.script
Here, I would like to
Members are interested to see / etc configuration files under a number of
They are scheduled to be careful after the meeting, how to get other
And inherited the right to read
If so, in the future you have a chance to write their own
Should also not difficult to specify a configuration file specifically for the script with a different
Share &of the
Here, if you do a know
And the source of the different
The next challenge was to undergo a
Also with that exec
source/fork
What difference does
Oh ... to understand
Perhaps more complicated, especially to link
File Descriptor
However, simply
Let script is executed on the same itinerary
But the end of the original schedule were
Will the termination of the original schedule, that is,
And source / fork the biggest difference between the
Ah, just from theory to understand
Perhaps not so easy to digest, as hands-on
Thinking implemented +
Oh come impress
Let us write two simple script, command, respectively,
#!/bin/bash
echo "PID for 1.sh before exec/source/fork:$$"
echo "1.sh: \$A is $A"
case $1 in
echo "using exec..."
exec ./2.;
echo "using source..."
echo "using fork by default..."
echo "PID for 1.sh after exec/source/fork:$$"
echo "1.sh: \$A is $A"
#!/bin/bash
echo "PID for 2.sh: $$"
echo "2.sh get \$A=$A from 1.sh"
echo "2.sh: \$A is $A"
Then, run the following parameters were observed result
$ ./1.sh fork
$ ./1.sh source
$ ./1.sh exec
Or, you can refer to
Another post on the
http://www.chinaunix.net/forum/viewtopic.php?t=191051
Well, do not forget to carefully compare the output of the reasons behind the different and oh
If in doubt, please discuss proposed to discuss
happy scripting! ^_^
---------------
Where poor
Ah, this time to relax
Do not speak too much
Let me talk about why to use
Many times, we
Operation, under certain conditions, one needs to perform multiple commands
That is, either do not perform
Either on the whole the implementation, not every order of the judge whether to execute the next command
Or, need to execute some commands to get exemption of subordinated priority
Such as arithmetic
At this time, we can introduce
Command Group
"(command group)
The concept of
Focus on multiple commands
In the shell command line in the
Most people may not care about
Between the two pairs of symbols
Although both groups can be more than one command for processing, but if the technical details
Is very different
Placed in the command group
To perform, also known as
nested sub-shell.
Is completed within the same shell
Also known as
non-named command group.
If, you have the previous chapter
And the source of the concept also remember the words of
It is not difficult to understand the difference between the
If the link the variables in the command group and other environmental changes
We can use according to different needs
Generally speaking, if the changes made are temporary
And do not want to affect the original or subsequent set, then we
nested sub-shell ,
On the contrary, the use of
non-named command group .
Yes, the light from the
command line
Difference on the finished, it easily enough
However, if these two
Or used in other areas of command meta
Regular Expression),
There are still many differences
But, I do not intend to go to shows
Slowly left to the reader to explore good
I'm here just want to add a concept that
function .
The so-called function, is to use a name to name a
command group ,
And then call the name to execute
command group .
From non-named command group to infer
You can probably guess my point is
You're so smart!
In the bash of
There are two ways the definition of
function function_name {
Second way
fuction_name () {
What a way to use does not matter, only if the meaning set out the name of encounter with the existing command or alias
Conflict, the second way may fail
But the way the second can at least play a small string of letters which function
For lazy people
How fun is not it
In certain extent, also called
Function &, but please do not use traditional programming function of the
Confused, after all, a great difference between the two
Only the same, we can always use
The defined name &to call them
If we shell operation
Need to constantly repeat the line quality in some order, we first thought
May be written in the script command
(shell script).
However, we can write
function ,
Then in the command line in the marked
function_name
The script can be when a sampan to use
If you just defined in the shell
function ,
In addition to cancellation can be unset function_name
Once out shell, function also followed Cancel
However, in
There are many benefits of the use of function
In addition to improving the implementation of the overall effectiveness of external script
Because it has been loaded
You can also save a lot of duplicate code
In short, if you will write multiple commands
For the call, then
You can function as
script ...
Moreover, introduced by the previous chapter
Order, we can define many useful
function ,
Then focus on writing in a specific file
Then, in the other
Load them using source and repeatedly perform
If you are a user RedHat Linux
Perhaps, already guess
/etc/rc.d/init.d/functions
This file is used for the Han
Well that should be easy to point, then writes it right this time for the time being
I wish you all a happy learning!
------------------
Where poor
Previous chapter we introduced
Different, this allows us to expand what
See more changes
What is clitoris
In the bash shell
Anti-quotes
Commands are used for replacement
(command substitution)
The so-called command substitution with our chapter learned about variable substitution are used to re-command-line
Complete the quotes in the command line, and then replace it the result
Reorganization command line
For example,
$ echo the last sunday is $(date -d "last sunday" +%Y-%m-%d)
This can easily be the date of the last Sunday
In operation, with
Does not matter, but I
Individuals &prefer to use
Easily with
Single quote
Out confusion, especially for beginners
Sometimes some strange shape in the display, the two symbols are identical
On end points
Of course, an experienced friend or one will be able to differentiate between the two
But, if better to avoid confusion
How fun is not it
Replace the multi-level complex in the
Need additional trip
Processing, and
Are more intuitive. For example,
This is wrong
command1 `command2 `command3` `
The original intention was to
command2 `command3`
Out to provide for first command3
Then the results to
command1 `command2 ...`
To deal with .
However, the real results in the command line is divided into
`command2 `
Correct input should be as follows
command1 `command2 \`command3\` `
Otherwise, replace
No problem
command1 $(command2 $(command3))
As long as you like, do not be a problem replacing the number of layers Rights
Death is not without side
Basically, all of the unix shell can be used in the use of
If written in shell script, its relatively high portability
Do not see the shell can be used for each
I can only tell you that if you
So, sure no problem
Next, let us
It ... it is actually used for variable replacement of Rights
Under normal circumstances
So what's not the same no
Would be more precisely defined the scope of the variable name, say
$ echo $AB
Was originally intended to first
The results of replacing out, and then fix a
Subsequent letters
However, on the command line, the real result is that only mention the name for the variable
If you use
No problem
$ echo ${A}B
However, if you only see
Can only be used to define the variable name, then you really underestimated
Are interested, you can first refer to
The essence of the article release
http://www.chinaunix.net/forum/viewtopic.php?t=201843
The sake of completeness, I use some examples to illustrate here
Some specific features
Suppose we define a variable
file=/dir1/dir2/dir3/my.file.txt
We can use
Are replaced by different values
${file#*/}:
Remove the first / and the left of the string
:dir1/dir2/dir3/my.file.txt
${file##*/}:
Remove the last / and the left of the string
:my.file.txt
${file#*.}:
Removed first. And left of the string
${file##*.}:
Removed the last one. And left a string
${file%/*}:
Removed the last bar / and the right of the string
:/dir1/dir2/dir3
${file%%/*}:
Remove the first / and the right of the string
${file%.*}:
Removed the last one. And the right of the string
:/dir1/dir2/dir3/my.file
${file%%.*}:
Removed first. And the right of the string
:/dir1/dir2/dir3/my
Memory method
Is to remove the left
Plate in the Kam
Is to remove the right
Plate in the Kam
The right side
Single symbol is t two symbols is the biggest match
${file:0:5}:
Extraction of the left-most five bytes
${file:5:5}:
Extraction of 5 consecutive bytes to the right of
We are also in the variable value can be replaced by a string
${file/dir/path}:
Will provide for the first dir
path:/path1/dir2/dir3/my.file.txt
${file//dir/path}:
Will all provide for the dir
path:/path1/path2/path3/my.file.txt
State variables can be assigned for different
Not set. Empty value
Non-null value
${file-my.file.txt} :
Not set, use
my.file.txt
For the return value
Null and non null values not be processed
${file:-my.file.txt} :
Not set or empty value, use
my.file.txt
For the return value
Non-empty value, no further treatment
${file+my.file.txt} :
Set to null or empty value, are used
my.file.txt
For the return value
Not be processed without setting
${file:+my.file.txt} :
Non-null value, use
my.file.txt
For the return value
When not set, and not to deal with null values
${file=my.file.txt} :
Not set, use
my.file.txt
As a return value, while
my.file.txt . (
Null and non null values not be processed
${file:=my.file.txt} :
Not set or empty value, use
my.file.txt
As a return value, while
my.file.txt . (
Non-empty value, no further treatment
${file?my.file.txt} :
Not set, then
my.file.txt
Null and non null values not be processed
${file:?my.file.txt} :
Not set or empty value, the
my.file.txt
Non-empty value, no further treatment
The above understanding is that you have to make clear
And null and
Assignment of these three states
And null on
Do not bring
Words, null is not affected
If the belt
Even null is also affected
Calculate the length of variable values
Get 27, because
/dir1/dir2/dir3/my.file.txt
Exactly 27 bytes
Next, a little bit for everyone mediated
Number of groups
In general, A = &abc def& just such a variable
Replaced by a single string
But instead
A=(a b c def) ,
Is defined as the number of groups
Number of groups refer to the following method substitution method
a b c def (
All group number
The first group of numbers
For the second group of numbers
Number of groups the number of all
The first group of numbers that
The length of the
),${#A[3]}
The fourth group of numbers
The length of the
The fourth main area is defined as the number of groups re-
Able to use bash's
Shell can greatly improve and simplify the processing power of the variables O
Well, the last to introduce
It is used for integer arithmetic
In the bash of
Integer operations generally have these symbols
Reduction. By
In addition to
Remainder operator
Were &AND.OR.XOR.NOT& operation
$ a=5; b=7; c=2
$ echo $(( a+b*c ))
$ echo $(( (a+b)/c ))
$ echo $(( (a*b)%c))
The variable name can be added in front of their
Symbol to replace, you can not
$(( $a + $b * $c))
Also get 19 results
In addition
Can also be used for different binary
If the binary. Octal
For computing it, but
Output are all decimal only
echo $((16#2a))
Turn decimal decimal
Example of a practical point of view and see
If the current umask is
So is the new file permissions
$ umask 022
$ echo "obase=8;$(( 8#666 & (8#777 ^ 8#$(umask)) ))" | bc
In fact, simply using
Can also be re-defined variable values, or for
a=5; ((a++))
Weight is defined as
a=5; ((a--))
a=5; b=7; ((a & b))
Return value
Common for
These symbols have the following test
Less than or equal to
Greater than or equal to
However, the use of
For the integer test, please do not tell
Integer test out some confusion
More tests I will be to introduce Chapter
How? Fun bar
So much for the time being
Described above, and no details of the status of each of the available
More to the reader La Reference Manual document
-----------------
Where poor
Before the start to be too
shell script
The positional parameter about
We already know the variable
(variable)
Is how to define and replacement, this not talked about more
But we also need to know that some variables are
Pre-determined, and its name is that we can not arbitrarily modify
Among them, including the positional parameter
In the shell script in
$0, $1, $2, $3 ...
These variables were extracted from the following part of the command line
script_name parameter1 parameter2 parameter3 ...
We can easily guess
Is to represent the name of shell script
The first argument is the later, and so on
Be subject to pay attention to the role of IFS
That is, if
After treatment was quoting
Then the positional parameter will change
The following example
my.sh p1 "p2 p3" p4
Key is the gap between the closed soft quote
Therefore, in my.sh
Is &p2 p3& and
Remember the first two chapters when we talk fucntion
I do not say it is the script in
Yes, function can be read as his own
Different from the script of
) postitional parameter ,
The only exception is
For example,
There is an assumption my.sh
Called my_fun, if
Middle Distance
my_fun fp1 fp2 fp3 ,
Then, function within
Is my.sh, and
Is not fp1
Better to write a simple my.sh script to see it
#!/bin/bash
my_fun() {
echo '$0 inside function is '$0
echo '$1 inside function is '$1
echo '$2 inside function is '$2
echo '$0 outside function is '$0
echo '$1 outside function is '$1
echo '$2 outside function is '$2
my_fun fp1 "fp2 fp3"
Then in the command line to run about in the
chmod +x my.sh
./my.sh p1 "p2 p3"
$0 outside function is ./my.sh
$1 outside function is p1
$2 outside function is p2 p3
$0 inside function is ./my.sh
$1 inside function is fp1
$2 inside function is fp2 fp3
However, the use of
positional parameter
, We should pay attention to some of the pitfalls Oh
Not replace the first 10 parameters
It replaces the first argument
Then fix a 0 thereafter!
That is, my.sh one two three four five six seven eigth nine ten such
command line ,
It is not ten
Oh, be careful ... be careful!
To catch ten words
There are two ways
First, using our method described in the previous chapter
It is to use
Second method is to
With the popular view, the so-called
Is to remove the positional parameter in the parameters of the left
Unaffected
The default value is 1, that is,
Are canceled or shift 1
The original
If the shift 3 is the abolition of the previous three parameters
That is, the original
Will become
That, dear readers
You say you want shift out how many arguments
Is available
When we have a basic concept of the positional parameter after ,
Then let us look at it the other relevant variables
The first is
It can catch the number of positional parameter
Using the previous my.sh p1 &p2 p3& as an example
Since p2 and
IFS is in between
soft quote
The value can be obtained 2
However, if p2 and
Not placed in quoting the words of
The value of 3 can be obtained
By the same token is the same as in the function of
Therefore, we often
shell script
In the script using the following method to test whether the parameters are read into
[ $# = 0 ]
If 0, it means
No parameters, otherwise it will have parameters ...
The next step is
Precisely speaking, only two
soft quote
The only difference, otherwise
Have said &all parameters
Good example
If run on the command line
my.sh p1 "p2 p3" p4
Can it wants to be p1 p2 p3 p4
However, if placed in
soft quote
In the words
May be &p1& &p2 p3& &p4& section of the three different words
May be &p1 p2 p3 p4& the whole string section of a single word
We can change it in front of my.sh, so that the contents are as follows
#!/bin/bash
my_fun() {
echo 'the number of parameter in "$@" is '$(my_fun "$@")
echo 'the number of parameter in "$*" is '$(my_fun "$*")
And then run. / My.sh p1 &p2 p3& p4 know
Where the difference
---------------------
Where poor
Finally, into the section of the double-digit
Along the way, it is very hard
It is also very happy
In this chapter, answers to questions before, let us understand a concept
:return value
We ran each of the next shell
Or function, at the end of the trip will be a value returned by the parent
return value .
Available in the shell command line
This variable is the most &new
A return value, that is the end of the trip just to return the value of the
Return Value(RV)
The value is between 0-255
By program
The set of proposed self-
If the script in
Used to specify the value of exit RV
If not specified, at the end of the last command
If the function in
Is replaced by return RV
Return Value
Effect is used to determine the exit status of stroke
(exit status),
There are only two
Words as &true
0, then for the non-
"( false )
A good example to illustrate the
Assuming the current directory files within a my.file
The no.file does not exist
$ touch my.file
$ ls my.file
# first echo
$ ls no.file
ls: no.file: No such file or directory
# second echo
# third echo
The example of the first echo is about
ls my.file
The RV, get
The second echo is about
ls no.file
The RV, then by the non-
The third is about the second echo
The RV, as
Value and, therefore, is
Each command will be returned at the end
return value
It! No matter what you run the command
However, there is a command
Specifically &to test certain conditions, to give
return value
For true or
It is the test commands!
If you use bash, please
command line
Hit man test or under
To understand the usage of this test
This is the most accurate you can be used as reference documents, and if listening to others say
Just for reference only
Now I simply make some help, all the rest
First, test the expression we call
expression ,
The command format, there are two
test expression
[ expression ]
Important to note
The gaps between the keys!
Which format do not use the so-called, is the same effect
I personally prefer the latter
Second, bash the
Tests on currently supported, as only three
String, that is, text
* integer:
Or a positive integer, does not contain negative or decimal point
Please be sure to clear the three novice differences, because
The expression used is not the same
To A = 123 case the variable
* [ "$A" = 123 ]:
Is a test string to test
1.2.3 whether the three consecutive
* [ "$A" -eq 123 ]:
Is an integer test, to test
Is equal to &one hundred twenty-three
* [ -e "$A" ]:
Is on file in the test, to test
The existence of
Third, when
expression
Test for &True
Time, test on the back
The return value, or send non-
0 (false).
If preceded by an expression
Exclamation point
Is when the expression is
False &before sending
Otherwise, send non-
At the same time, test also allows multiple laminated test
* expression1 -a expression2 :
When two exrepssion are all
Before sent 0, otherwise send non-
* expression1 -o expression2 :
Just as one exrepssion
To send 0, and only two are for the
Only send non-
For example,
[ -d "$file" -a -x "$file" ]
Is expressed as
Is a directory. And both
Permissions, test will be for
command line
When used in test
Please do not forget the command line of the &re-
That is encountered will be handled meta
Re-formation of the command line
This feature is in the second and the fourth chapter I have repeatedly stressed
For example, if
Encounter variable or command substitution, if can not meet
expression
Format, the result will be syntax error
Good example
[ string1 = string2 ]
The test format
= Number in the string on both sides must be
Including the empty
Free soft quote or
hard quote
There is no definition, or set to an empty string, then proposed
That the following wording will fail
$ [ $A = abc ]
[: =: unary operator expected
This is because the command-line hit
When the meta
Value, and then restructuring the command line
It becomes
Thus there is no string left = number exists
Syntax error in the resulting test!
However, following the establishment of written law is
$ [ "$A" = abc ]
This is because after the reorganization of the command line results
[ "" = abc ]
We left the =
soft quote
Get an empty string, and let
Syntax passed
Readers pay attention to these details dwellers Oh sure, because the slightest mistake
Test results will lead to changed samples!
If you are not a lot of experience on the test, then
That when using the test as this one may wish to use
Encountered in the test if the variable substitution
With a soft quote is the safest!
If you are quoting the words of unfamiliar
Please re-review the contents of Chapter IV bar
Test on the use of more
See the man page now!
Although a lot of eloquent talk about, perhaps you are still muttering
That ... that
return value
You Shayong ah?!
Good question!
:return value
The role can be big! If you want your shell variable
Smart &, then
Depends on it
With the return value, we can let
According to different states doing different situation when
At this time, it let me answer it in this chapter revealed
Are used to &set up
Use of multiple command line
* command1 && command2 :
That means only command2
The implementation of the conditions
* command1 || command2 :
That means only command2
The implementation of the conditions
Come to a good example
$ [ -n "$A" ] && echo "yes! it's ture."
yes! it's ture.
$ [ -n "$A" ] && echo "yes! it's ture."
$ [ -n "$A" ] || echo "no, it's NOT ture."
no, it's NOT ture.
:[ -n string ]
Is to test the string length is greater than
The example of the first
The reason why the command line will echo the command to implement its right
Because a test on the back of the
But the second will not be executed because the
Back to the results of non-0
Echo will be the implementation of the right
Because the test is sent back to the left of the non-
In fact, we in the same command line
More than available
To build it
$ [ -n "$A" ] && echo "yes! it's ture." || echo "no, it's NOT ture."
yes! it's ture.
$ [ -n "$A" ] && echo "yes! it's ture." || echo "no, it's NOT ture."
no, it's NOT ture.
How, from this moment
Do you feel that our shell is
Very smart &does
Well, the last
Layout-wide desire for an Exercise for everyone
The following judgments are
Are given with the value, the look is less than
Otherwise send
too big! :
$ [ -n "$A" ] && [ "$A" -lt 100 ] || echo 'too big!'
If I cancel the A
Logically speaking, should not send text fishes ah
Because the first condition is not established
$ [ -n "$A" ] && [ "$A" -lt 100 ] || echo 'too big!'
Why do the above results obtained
Also, how does the solution
Modified many ways, one of the methods can be introduced by Chapter VII of the
command group ...)
Fast! Tell me the answer! No way the rest of
--------------
Where poor
Before this time the topic of my CU
Version has been a description of
http://bbs.chinaunix.net/forum/24/375.html
This time I do not rewrite, and will post the contents of the
Copy &down it wants to
--------------
About I / O redirection, may wish to let us know what
File Descriptor (FD) .
Program operations, in most cases the data are
Processing
Where the data read into? And
Where to send it
file descriptor (FD)
The function of the
Program in the shell
FD is probably the most frequently used three
0: Standard Input (STDIN)
1: Standard Output (STDOUT)
2: Standard Error Output (STDERR)
In the standard case, these
Respectively, with the following equipment
stdin(0): keyboard
stdout(1): monitor
stderr(2): monitor
We can use the following command to test the next
$ mail -s test root
this is a test mail.
please skip.
At the same time with the press crtl
It is clear, mail programs read the data into the
That is, from stdin
Read into the
However, each program is not necessarily
Related to the same mail from
Because the program of the parameters can be read from the file into the stdin, such as
$ cat /etc/passwd
However, if
After the file parameter is not how it
Oh, please play with your own La
Please note that output data where to go, and finally, remember to press
As for the stdout and
Ah ... so I'm free adjourned to the bar
Or, are there any older generation do to play Solitaire
--------------
Along the text adjourned, the book connected to a back
Believe, after the previous exercise
Stdin and you
It should be easy to understand
Then, let us read
In fact, stderr little hard to understand
The truth is the &error message
Where to send it to edge
For example, if the parameter is read into the file does not exist
Then we saw on the monitor
$ ls no.such.file
ls: no.such.file: No such file or directory
If a command while generating
And stderr it
It is not simple, are sent to the
To just fine
$ touch my.file
$ ls my.file no.such.file
ls: no.such.file: No such file or directory
So far, about
And its name. There associated equipment
I believe you have no problem now
Well, let's see how to change these
The default data channel
To change read into the data channel
So read from the specified file into the
To change the outgoing data channel
(stdout, stderr),
So that the output to the specified file
For example,
$ cat & my.file
Is read into the data from the my.file
$ mail -s test root & /etc/passwd
Is from the / etc / passwd read into
As a result, stdin will no longer be from the
Read into, but read from a file into the
Strictly speaking
FD before the need to specify a symbol of
Can not have gaps between
However, because 0 is
Default values, so
Is the same!
The good understanding of it
That, if using two
This is the so-called HERE Document, it allows us to enter a text
Until the read
After the specified string
For example,
$ cat &&FINISH
first line here
second line there
third line nowhere
In this case, cat will read into the
Row sentence, and does not derive from
Read into the data and have to wait
Listen next time decomposition
--------------
Time again to talk about the ancient
When you get to know
The original stdin is to change the input channel after data
I believe it is not difficult to understand the following two redirection
The former is to change the data output channel stdout
The latter is to change the data output channel stderr
Both the original data to be sent to the monitor output to the specified file to turn
Since 1 is
Default values, so
Is the same, are changed
Ls with the last good example to illustrate
$ ls my.file no.such.file 1&file.out
ls: no.such.file: No such file or directory
This monitor on the left
Only. Because
Go to the written file.out
$ ls my.file no.such.file 2&file.err
This monitor on the left
Because stderr written into
file.err .
$ ls my.file no.such.file 1&file.out 2&file.err
This monitor to be nothing
Because the stdout and
Gave to the file to the
It seems to understand
It is also not difficult to it! Is not it? Did not lie to you now
However, some areas still have to pay attention to what the
First of all, the problem is also written
For example, following the example :
$ ls my.file no.such.file 1&file.both 2&file.both
Are also the words in the written file.both
Is to take &cover
Was written in front cover
Let us assume that a stdout and
At the same time writing good case file.out
First, write stdout
Characters
Then write to stderr
Characters
So, this time the original
In front of the 6 characters to be
Overwritten
Well, how to solve it
The so-called mountain does not turn the road turns. Road does not turn people turn Well
We can change a mind
Will lead into stderr
Or to lead into stdout
And not everyone in the rush with a file, not on the list!
! Rights is one such
Times is to stderr
For output
Times is to stdout
For output
As a result, operations can be changed before the error
$ ls my.file no.such.file 1&file.both 2&&1
$ ls my.file no.such.file 2&file.both &&2
In this way, not to the satisfaction of all of you
However, light to solve the problem while writing is not enough
We also have other skills you need to know
Story does not end, do not go away! Advertisement
We come back ...!
--------------
The do not speak I / O Redirction, about the Buddha Bar
Is there a mistake?! Whether the head capsule burned human network
Buddhism's highest level, is
End up achieving nothing. &As to which of the four blocks is empty
I do not know, because I'm not to that realm
However, this &empty
Words, it is worthy of repeated play of
Sex is zero. Kongjishise!
Well, if the donor can understand
Empty &Zen
It is not far away from fruition
In the Linux file system
There is a device file is located
/dev/null .
Many people have asked me what stuff? Well, I told you
That is &empty
Yes! Is null the empty space
Gordon Does donor have missed it all of a sudden it? What, then congratulations
The null in
I/O Redirection
It can be very useful in
If FD1 with
Go to / dev / null to
Stdout and can be
Get gone away
If FD0 received
To, that is read into
For example, when we execute a program when
Screen will also send stdout with
If you do not want to see
Do not want to save to a file
$ ls my.file no.such.file 2&/dev/null
To the contrary
Just want to see it stderr
Is not easy! Get the stdout
On the line
$ ls my.file no.such.file &/dev/null
ls: no.such.file: No such file or directory
That Next, run the program only if the simple
Do not want to see any output
Oh, here left hand not talking about nothing, the last program
Special gift a nice ring!
In addition to using
&/dev/null 2&&1
In addition, you can be so
$ ls my.file no.such.file &&/dev/null
Finished the Buddha, the next
Let us look at the situation as follows
$ echo "1" & file.out
$ cat file.out
$ echo "2" & file.out
$ cat file.out
It appears that we redirect
Or stderr into a file
Never seem to get only the results of the last import
Well, the content of it before
To resolve this question is very simple provided you, the
$ echo "3" && file.out
$ cat file.out
Thus, the goal was redirected and not lose the contents of the file
The new content is constantly increasing in the last side to
However, if you go back to single again
Redirecting, then
The old content will still be &washed
Out of it!
Then you have how to avoid it
Backup! yes, I heard! However,
Is there a better you
Since such a fate with the donor, the old magic bullet satisfied send you a kit, right
$ set -o noclobber
$ echo "4" & file.out
-bash: file: cannot overwrite existing file
That, how to cancel this
Restrictions &do
Set + o on the line into
$ set +o noclobber
$ echo "5" & file.out
$ cat file.out
That does not cancel but there are ways ...
Temporary &cover up the target file to write
Oh, Buddha said
Can not report too!
Kidding. Just kidding
Well, long expected a shortage of people is!
$ set -o noclobber
$ echo "6" &| file.out
$ cat file.out
Noted that there is no
Followed by the two
Oh, can not have gaps between
Take a deep breath breathing about it
Again there is a problem of it to you to fathom
$ echo "some text here" & file
$ cat & file
some text here
$ cat & file & file.bak
$ cat & file.bak
some text here
$ cat & file & file
$ cat & file
Ah?! Noted that no
Finally, the cat command to see how the
Actually empty?!
why? why? why?
Do not be late next class Hello
--------------
Dangdang when
Hello class
:$ cat & file & file
After the contents of the file originally had been washed off the results!
To understand this phenomena is not difficult, it is only
Just a matter of
In the IO Redirection
And stderr of the pipeline will be
Please enable JavaScript to view the
Computer industry, hacker culture has been a huge shock. When the software license and copyright to become industry standards, the programmers are no longer free to use as before and change other people's software. FUD, or Fear, Uncertainty, Doubt, t
Source: http://os.51cto.com/art/820.htm Linux shell script based learning about the third, in front of us shell commands and process control, the lack of space did not speak process control, process control today introduced here is only the
Transfer from: http://blog.csdn.net/wenrenhua08/archive//5857347.aspx Shell script has recently been busy studying, I feel learned a lot, to share this with you. Script iout.sh #!/bin/sh SHDIR=&$(dirname -- $(readlink -f -- &$0&))
1. Linux 1.1 syntax based scripting a basic introduction to 1.1.1 at the beginning of the line program must begin with the following (must be square in the first line of file): #! / Bin / sh Symbol #! Behind it to tell the system parameters are used
1. Linux 1.1-based syntax of scripting a basic introduction to 1.1.1 at the beginning of the program must start with the following line (be the first line in the file side): #! / Bin / sh Symbol #! Used to tell the system behind the argument that it
Why the shell programming In Linux systems, although there are a variety of graphical interface tools, but sell is still a very flexible tool. Shell is not only the collection of commands, and is a great programming language. You can use the shell to
Transfer from Source: Linux Commune of: Linux http://www.linuxidc.com/Linux/7.htm 1. Linux based scripting 1.1 Syntax Basics 1.1.1 at the beginning Program must begin with the following line (be the first line in the file side): #! / Bin /
5. Quotation marks to pass any parameters to the program before the program will expand wildcards and variables. This means that the so-called program will expand the wildcard (eg *) replace the appropriate file name, it is replaced by the variable v
exec bash and source are all internal commands (builtins commands), enter man exec in bash or man source internal command can view all of the information. bash shell command into two categories: external command and internal command. External command
Copyright (C) , All Rights Reserved.
版权所有 闽ICP备号
processed in 0.039 (s). 13 q(s)}

我要回帖

更多关于 申愽亚洲667878 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信