Makes it easy to overlook some of the basics of shell

2010-07-29  来源:本站原创  分类:OS  人气:177

Always felt that his own shell scripts can be written, ms is a bit narcissistic, and recently read some expert to write the script, they will have found a bit unusual difficulty. Can not help but could not help but ask yourself, will determine several conditions, several cycle is shell programming expert What? Ever once again came to CU shell version, there are indeed many very basic knowledge, are their own do not understand the need to sink to in-depth study center / review how these basic things:

When you're at the command prompt, type a command / command line after, shell work to be done is:
1. Parsing command line
2. Dealing with wildcard characters (wildcards), redirect (redirection), pipe (pipes) and job control (job control)
3. Search for and execute the command

User login, the user commands to interact with the computer relationship: the command process ---> Shell program ---> UNIX kernel ---> Computer Hardware

Several rare symbol:

cmd &> file # &> that the cmd's stdout and stderr are written to the file

cmd> file 2> & 1 # 2> & 1 basic Ibid, remember that 2> & 1 can not have spaces between

n <> file # open file for reading and writing, and the distribution of the file descriptor n to the document. If the file does not exist, will automatically create

= ~ # Regular expression matching, this must be bash3.0 later version, and must be used in the double in brackets [[]], if [["$ IP" = ~ "^ [0-9] + \. [0-9] + \. [0-9] + \. [0-9] + $ "]] & & echo" ok "| | echo" error "

================================== Pipelines and sub-shell =========== ========================

On the bash, in a pipe brace code segment (block) is run in a sub-shell.
# Ls | (read firstline; read secondline;)
# Echo "First line is $ firstline; second line is $ secondline" # here to see is a blank

Pipe on both sides of the code "block", not just including the "braces" enclosed blocks, but also while, for other loop in the "block", which is why it has frequently been asked why the assignment in the while loop variables, see the entry into force of the loop outside Quemei not cycle itself, but because both sides of this cycle in the pipeline Kazakhstan

As a child process will run the pipeline, not to change the script variables.
1 variable = "initial_value"
2 echo "new_value" | read variable
3 echo "variable = $ variable" # variable = initial_value

Here can read variable <<<"new_value" to replace

LANG = C &, or export LANG = C & it does not affect the current shell, powerless to change the LANG environment variable to a command if the pipeline had an exception and fail in the middle, then the pipeline will be prematurely terminated. This kind of behavior is called the broken pipe, and this state will send a SIGPIPE signal.

bash produced in several sub-shell case

1. Cmd | (cmd_list1; ... cmd_listn;)

(Cmdlist;) | (cmd list;)

Note that these two formats, the process of the relationship between the different, try the next (sleep 10;) | (sleep 20;) and sleep 10 | (sleep 20;) see next process, differences in the relationship between

2. Function func () ()

func &

3. () &

4. (Func &) & This will create two sub-shell

5. (Cmd1; cmd2) # cmd here must be greater than one (ie cmd group) will be subshell

6. Su user

================================== Pipelines and sub-shell =========== ========================

For the location parameter, is greater than or equal to 10 positional parameters must be enclosed with braces, such as echo $ (10). To access the command line, the last parameter, you can ${!#}, or i = $ #, $ (! I), $ (! XX) said indirect reference

====================================== ========== Block ==============================

Use curly braces () implementation of a series of commands, and if we do not wrap, I remember the back of each kicked must add a semicolon; including the last command, otherwise you will get an error such as:

$ (Echo "xyz") # bash will think of you entered is not over

$ Vi

(Echo "xyz")

$. /

. / line 6: syntax error: unexpected end of file. If the commands are separated by a newline, the last exchange between the command line and), you do not need a semicolon

====================================== ========== Block ==============================

============================== Here document ================== ======================

1. Note: the end of the limit string, is the last line here document limit string, a character must begin in the first place. It can not have any front in front of the blank. And in this limit string behind the blank will cause abnormal problem. blank will prevent limit string recognition.

For example, sometimes you to align, nice layout of some:

function test ()
cat <<EOF
hello, world

return 0


exit 0

When run this script, will get an error: "syntax error: unexpected end of file", there must be EOF on the first line to avoid this error

2. - Option to mark a here document limit string (<<-LimitString), can inhibit the output tab front
(Not spaces). This can increase the readability of a script.

3. Here document supports parameter and command substitution. So here document can also be a message to the body pass different parameters,
This will modify the corresponding output. When the "limit string" is quoted or escaped then disable parameter replacement, such as

cat <<'EOF'

cat <<"EOF"

cat <<\ EOF all have the same effect, this time inside the here document a reference to the corresponding variable substitution and so will not do the replacement, but remember that the end of the EOF does not need to identify with the symbols like these escape

4. Comment blocks of code, each line with # to be more than easy to use more

: <<CommentHere

echo "hello, world"

# Echo "hello"


============================== Here document ================== ======================

In the command line, the exclamation mark "!" In double quotes in the command will error (Translator's Note: For example: echo "hello!"). Because the exclamation mark is interpreted into a historical order. However, in a script file , so writing is correct, because in the script file in Bash history mechanism is disabled.

bash some of the new features:

[["Abc"> "aba"]] & & echo true # [[]] values can be compared not only the size, you can also compare the size of the string

++++++++++ String handling

We can also variable in the string for replacement:

$ (File / dir / path): will replace the first dir path: / path1/dir2/dir3/my.file.txt

$ (File / / dir / path): to replace all the dir path: / path1/path2/path3/my.file.txt

$ (Kk / / [! 0-9] /)

====================== ======================== Bash in the colon ===========

Space Command, is the bash built-in command, to do nothing in order, quite and true, return 0
General Usage:
1. Endless loop while: do oper_lists; done
2. In the if / then provide placeholder
if condition
then: # trigger a branch
3.: $ (Variable = "xxx") # in a binary command to provide a placeholder
: $ (Variable: = "xxx") # $ (xxx: =) of the different states of the variable assignment, the general wants: combination

4. Combined with comments bash here document block
: <<EOF
echo "hello, world"

The somewhat similar to the c / cpp compilation in the use of pre # if 0 .... # endif to comment a large block of code

====================== ======================== Bash in the colon ===========

ps Why bash the time to see one before - what?
This indicated that this is a login shell
If only bash, that a non-login shell, try to use su xxx, and then click ps

=========================== ====================== Function =====

1. In the function, declare the variable, is the local if not specified, and the function can also be used in vitro

2. In the function call another function, called function can be defined after the function call / declaration (bash function declaration is not the concept). For example:

function a ()


echo "i'm a"



function b ()


echo "i'm b"


3. But if you have a public library, you must call the public library, public library to perform the function, such as:

.. / Functions


Can not


.. / Functions

=========================== ====================== Function =====

  • Makes it easy to overlook some of the basics of shell 2010-07-29 Always felt that his own shell scripts can be written, ms is a bit narcissistic, and recently read some expert to write the script, they will have found a bit unusual difficulty. Can not help bu

  • Easy to overlook the framework of development 2009-10-14

    Easy to overlook the framework of development

  • MySQL non-source learning: the cursor on a stored procedure is easy to overlook two points 2011-09-27

    Today, write a little bit complex stored procedures easy to overlook the points hit two share. If you have just encountered the same problem cheese can be less entangled bit, so what's the technical content of the wood. . . 1, an example of a stored

  • Easy to overlook the details of the programming 2010-06-04

    In the IDE environment, so that we in the programming code to reduce a lot of knocking on the wrong hand, but some details still can not be ignored. This is precisely what the programming produced BUG. Suppose there is no syntax error under the premi

  • HttpClient's easy to overlook the details - the connection is closed 2009-10-02

    HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(""); try { client.executeMethod(method); byte[] responseBody = null; responseBody = method.getResponseBody(); } catch (HttpException e) { // TODO Auto-g

  • SEO of the most easy to overlook the details of the 2010-11-09

    Baidu algorithm of three years, playing SEO nearly five years, and also called a SEOER, from awareness to understand the SEO process found a shift in the year 2010, found that people who understand SEO and proficient in the increase in non-section, a

  • Managed Server is easy to overlook the four selected learning 2010-11-20

    1 managed to sign a strict contract Custodian must sign strict contracts, specifying the responsibilities, rights. For example, service providers or mobile machines to change machine debug IP three days in advance to notify the user in a timely manne

  • Object-oriented flex easy to overlook the place in 2010-12-26

    1 covered, the method name, parameter number, type, sequence of these is the method signature, as long as the method signature can cover. However, java, C + +, provisions that allow sub-classes will cover the return type is defined as a subtype of th

  • HttpClient easy to overlook the details - connection closed 2011-09-29

    Java code HttpClient client = new HttpClient (); HttpMethod method = new GetMethod (""); try { client.executeMethod (method); byte [] responseBody = null; responseBody = method.getResponseBody (); } Catch (HttpException e) {

  • Using Jquery needs to achieve as you show hidden (super easy) 2008-11-20

    1. First of all you need to import the Jquery of the package, <script src=" You download jQuery package of native address " type="text/javascript"> </ script> <select name="promotion"> <! - Here Please no

  • Architect of the road (3) --- architect responsibilities 2009-03-13

    3 architect duties Recent months have seen CSDN on CTO club, which is a better choice. My attitude with great reverence, read a statement about people's cow. Have a buddy there to launch a topic: "CTO, how long you did not write the procedure?."

  • hibernate cache 2009-08-17

    hibernate The session provides a cache for each session, twice on the same id to load, does not send 2 sql to the database, but the session closed, a cache becomes ineffective. SessionFactory level 2 cache is a global cache, it can be used under diff

  • Management of software development experience 2009-10-20

    From the graduation date, the size of the project done something, there are a lot of the joy of success, many failures. This year, due to work, I Software In his capacity as project leaders participated in the access network to develop a unified netw

  • AJAX also has potential safety problems to talk about the security of AJAX 2009-02-22

    Web developers do not notice from the "AJAX (Asynchronous JavaScript And XML)" brought about by passion. No ability to create that kind of intelligence, like Google Suggest website or Like Gmail as Web-based applications, in large part thanks to

  • JSTL Learning Summary 2009-05-03

    JSTL There are plenty of easy to overlook areas of study Summary: 1 FOREACH Learning: <c:forEach items="${ personList }" var="person"> <tr> <td> $ ( </ td> </ tr> ........ </ c: forEach> In

  • <Clean Code> Method Summary 2009-06-19

    1. Method to be short. The best control in less than a few lines. For example: public static String renderPageWithSetupsAndTeardowns( PageData pageData, boolean isSuite) throws Exception { if (isTestPage(pageData)) includeSetupAndTeardownPages(pageDa

  • Url address to use to achieve URLRewrite pseudo-static 2010-03-20

    1.1URLRewirte the usefulness of 1. To meet the requirements of search engines. 2. Hide the technology to improve the site portability. 3. To meet the aesthetic requirements (personal feeling of this useful too far-fetched). 1.2 Project Deployment 1.

  • Dynamic DataSource Routing --- Spring to connect multiple data sources 2010-03-20

    Copied from: Spring 2.0.1 introduced an AbstractRoutingDataSource. I believe that it deserves attention, since (based on frequent questions from clients) I have a hunch that there ar

  • [Change] hibernate 2 cache Raiders 2010-03-31

    Many people are not understanding the secondary cache, or a misunderstanding, I always wanted to write an article introduce hibernate secondary cache, and today, could not. My experience mainly from hibernate2.1 version of the same basic principles a

  • AJAX is also a safety hazard to talk about the security of AJAX 2010-03-08

    Web developers will not notice the "AJAX (Asynchronous JavaScript And XML)" brought passion. To effortlessly create as smart as Google Suggest or website Like Gmail Web-based applications as, in large part thanks to this technology. However, alo