Under unix shell programming (1)

sponsored links
* Shell What is this?

Any invention has for user interface. User interface for UNIX is the Shell (DOS's command are familiar with it, but more powerful UNIX-to). Shell provides the user input commands and command parameters may be the result of the environment.

To different needs, UNIX provides a different Shell. Most of the current UNIX support BourneShell, the following tutorial on to BourneShell (Bsh), for example, step by step the taste of the power of UNIX Shell, precedence of its powerful charm, to a more convenient and flexible management, application of the purpose of UNIX.

1.UNIX the interaction kernel and Shell Method

Start UNIX, the program UNIX (core) will be transferred to computer memory, and has been retained in memory until the machine shut down. In the boot process, the process init will enter run in the background until the machine shut down. The program check file / etc / inittab, the document lists the terminal connections and characteristics of each port. When they find an active terminal,, init program calls the getty program such as landing terminal display login information. (Username and passwd), enter password, getty calls login process, which is based on the file / etc / passwd to verify the contents of the user's identity. If the user authentication, login process to the user's home directory set to the current directory and to control a series of setup. setup program can be specified in the application, usually a setup program for the Shell process, such as: / bin / sh or Bourne Shell (command out, huh, huh).

Have been controlled, Shell program to read and execute files / etc / .profile well. Profile. These two documents were established within the system and the user's own work environment. Finally Shell command prompt is displayed, such as $. (This is a bsh example, if csh, as. Cshrc, ksh is. Kshrc, bash is. Bashrc, etc.)

Note: (may wish to / etc / .profile and. Profile as DOS's autoexec.bat or config.sys files)

When the shell exits, the kernel transfers control to the init program, the program auto-login to restart the process. There are two ways to shell out, one user exit command execution, and second, the kernel (such as root with the kill command) to issue a kill command to end the shell process. shell out, the core collection of users and uses of resources.

User login, the user commands to interact with the computer relationship: the command process ---> Shell program ---> UNIX kernel ---> computer hardware. When the user enters a command, such as $ ls, Shell will locate its executable file / bin / ls and its transfer to the kernel implementation. Core to produce a new child process is executed through / bin / ls. When the program finished, the kernel process and the removal of the child to the parent to control the process, which Shell program. For example, run:

$ Ps

The command will be listed in the user process of being implemented, that Shell program (down elaborate, do not worry now) and the ps program. If implemented:

$ Sleep 10 &
$ Ps

The first command will produce a child in the background and the implementation of the sleep process. ps command will show the child process.

Whenever a user executes a command, it will generate a child process. The child and the parent process of the implementation process or Shell has nothing to do, so that Shell can do other work. (Shell is the user's intent is to tell the kernel, and then the why why:)) Now windows has a plan Ren Wu (in a fixed time, date Zidong execution of a task), in fact, very early Jiuyouzhege UNIX-order functions, that is, automatic implementation of the so-called Shell. Some UNIX resources, such as cron Shell procedures can be performed automatically without user involvement, (This function if the / var / spool / crotab directory).

Crontab procedures for system administrators is very useful. Cron service for the planning process at a specific time (month, day, week, hour, minute) run. Root's crontab our example. Root user's crontab file on the / var / spool / crontab / root, its format is as follows:

(1) (2) (3) (4) (5) (6)
0 0 * * 3 / usr / bin / updatedb
1. Min (0-60)
2. Hours (0-23)
3. Day (1-31)
4. Month (1-12)
5. Week (1-7)
6. 2.Shell to be running the functions and characteristics of a> command line interpreter 2> to use reserved words 3> use the Shell metacharacters (wildcards)
4> may be processing an order 5> use the input and output redirection and pipes 6> to maintain a number of variables 7> Runtime Environment Control 8> support Shell Programming

For the "command line interpreter" is not to say that the shell prompt (for example :"$","%","#", etc.) and enter the unix command line, Shell will receive the user input.

"Using reserved word": Shell have some words of special significance, for example, Shell script, do, done, for the words used to control the cycle of operation, if, then operate and other control conditions. Shell reserved words as the environment varies.

"Wildcard": * Match any position? Match a single character
[] Matches the range or list of characters such as:

$ Ls [ac] *

Will be listed within the character begins to ac all the files $ ls [a, m, t] *
Will be listed with e, m or t at the beginning of all documents

"Process order": When a user input command, Shell reads the environment variable $ path (usually the user's own. Profile is set), the variable contains the command executable file that may exist in a directory listing. shell command from the directory to find the corresponding executable file, then the implementation of the document sent to the kernel.

"Input and output redirection and pipes": Redirect function with DOS redirection feature:

">" Redirect output "<" redirect input

The pipe symbol, is a local unix powerful, symbol is a vertical line :"|", Usage: command 1 | command 2 of his function is to first implement the results of the command command 1 command 2 input passed as a command 2, for example:

$ Ls-s | sort-nr | pg

This command lists all the files in the current directory, and the output sent to sort order as input, sort order by number in descending order to sort the output of ls. Then sorted the contents of the command sent to pg, pg command to display the sort command displays the contents sorted.

"Maintenance Variables": Shell can maintain a number of variables. Variable number of data stored for later use. Users can use the "=" to the variable assignment, such as:

$ Lookup = / usr / mydir

The command to build a lookup of the variable named and given their assignment / usr / mydir, since users can use the lookup command line instead of / usr / mydir, for example:
$ Echo $ lookup
The results showed that: / usr / mydir

In order for the child process variables can be used, available exprot command, for example:

$ Lookup = / usr / mydir
$ Export lookup

"Run Environmental Control": When a user login after boot shell, shell for the user to create a work environment, as follows:

1> When the login process after activation of the user shell, for users to set environment variables. From / etc / profile and. Profile files read in these documents usually use the terminal type $ TERM variable is set, use $ PATH variable to find executable file path Shell.

2> from / etc / passwd file or the command line start the shell, the user can specify certain parameters to the shell program, such as "-x", can be displayed before the command of the command and its parameters. Details behind these parameters.

"Shell programming": This article introduces the contents.

shell itself is a language (* can first be understood as a combination of unix commands, together with class C of conditions, such as process control loop statement, similar to the dos batch, but more powerful), users can shell programming (scripts, text file), the completion of specific tasks.

SHELL variables

Below we detail Bourne Shell programming:

Since the Bell Labs design a Bourne Shell. Since then, many manufacturers designed according to different hardware platforms too many versions of unix. However, in many versions of unix, Bourne Shell has been consistent.
1> Bsh start: user login, the system under the file / etc / passwd of the user information about the items start Shell. For example, a user's information in the passwd entry is:

ice_walk:!: 411:103: Imsnow, ice_walk: / home / ice_walk: / bin / bsh

Indicates that the user name is ice_walk and other information, in the last "/ bin / bsh" that type of environment is the user's sh bsh, then boot the. At the start or the Executive (including the following shell program that we want to talk about - scripts) can use the following process some of the parameters, we 11 Description:

The output of all variables-a-c "string" read command from the string to use non-interactive mode-e-f shell file name against the definition of production-h-k-i interactive mode to set options for the command-n implementation read command, but not limited model implementation-r-s command from standard input, the implementation of a command-t, and then exit shell
-U in the replacement, the use of a variable is not set to be error-v shows the input line-x shell trace mode, display the command execution

Many models can be combined to use, you can try, but-ei if not, why do you say?

Using the shell set to set or cancel the option to change the shell environment. Open the option to use "-" to close the option to use "+", most unix permission to open or close a, f, e, h, k, n, u, v and x options. Shell has already set up if, the options, run:

$ Echo $ -

Bsh each user's home directory has a. Profile files, you can modify the file to modify the shell environment. In order to increase the path of an executable file (such as / ice_walk / bin), you can put the following code to join. Profile of

PATH = $ PATH: / ice_walk / bin; exprot PATH

. Profile in the shell environment variables mean the following:

CDPATH implementation of the cd command search path used when the user's home directory HOME IFS internal field separator, generally spaces, tabs, or line breaks MAIL specify a particular file (mailbox) of the path, a UNIX mail system using the PATH find command search path (with the config.sys dos the path)
PS1 main command prompt, the default is "$"
PS2 from a command prompt, the default is ">"
Use terminal type TERM

2> Bsh in special characters and their meanings

In Bsh in a group of non-alphabetic characters. The use of these characters is divided into four categories: as a special variable name, resulting in the file name, data or program control and character references, and escape control. They allow users to use the minimum amount of code Shell complex task.

*> Shell variable names using special characters $ # sent to parameter number $ command Shell - Shell startup or set in order to provide options for $? On a command and returned to the value of the $ $ $ No. current shell process ! a child process ID $ @ all the parameters, each with a pair of brackets from $ * All arguments, enclosed in double parentheses location parameters $ n, n, said the current shell name location $ 0 *> generated file name Special characters include "*","?","[]", above mentioned, many times before.
*> Data or program control using the special characters> (file) output redirected to a file (no files are created, there is coverage)
>> (File) output redirected to a file (do not you create, there is appended to the end of the file)
<(File) input redirection to a file; command separator | pipe break & runs in the background (for example: sleep 10 &)
`` Command substitution, redirects the output of one command to another command as a parameter *> for reference or to escape special characters

Bsh in single quotes '' and double quotes "" to the special character or by reference to a blank-separated words to form a simple data string. Using single quotes and double quotes in double quotes is the difference between the contents of parameters and variables can be replaced. Escape character is the same.

$ Echo "$ HOME $ PATH"
The results showed that $ / u / ice_walk / bin: / etc: / usr / bin
The $ echo '$ HOME $ PATH' results show $ HOME $ PATH

shell escape character is a "\", that was the character does not have special meaning or is not a function of shell

$ Echo \ $ HOME $ PATH
The results were $ $ HOME / bin: / etc: / usr / bin:

3> Bsh variables

We earlier quoted in a number of local variables, when Shell encountered a "$" symbol time (not to be quoted or escaped), it was considered a variable. Whether the variable is the environment variables or user-defined variable, the variable name in the command line variable value to be replaced. For example, the command: ls $ HOME directory will be listed under the variable HOME corresponding file. Users can command line variable substitution anywhere. Including the command name itself, for example:

$ Dir = ls
$ $ Dir f *

Will be listed with f at the beginning of the file.

Now a detailed description of the variables under the Bsh. Bsh has four variables: user-defined variables, location variables (shell parameters), pre-defined variables and environment variables.

User-defined variables:

User-defined variables composed of letters and underlined, and variable names can not be the first character number (0 to 9). Like other UNIX name, variable names are case-sensitive. Users can use the command line "=" to the variable assignment, for example:

$ NAME = ice_walk

Assigned to the variable NAME as ice_walk, when in the application of the variable NAME, the NAME before the "$" can be, as has been said, no nonsense (not to mention my nonsense, what is crucial is not worked as a teacher: (). Can variables and other characters form a new word, such as:

$ SUN = sun
$ Echo $ (SUN) day

Shell variable in the application of the time, both sides in the variable $ name followed by (), in order to more clearly show to the shell, which is a real variable, in order to achieve a string of merger and other functions.

The results show: sunday (be careful not to echo $ SUNday, because SUNday variable not defined, implemented under the reader test result) on the command line user can simultaneously assign multiple variables, separated by spaces between the assignment statement:

$ X = x Y = y

Note that the variable assignment is carried out from right to left

$ X = $ YY = y
X's value is y
$ X = z Y = $ Z

Y's value is empty (when the variable is not assigned, shell does not error, but the assignment is empty)

Users can use "unset <variable>" command to clear the value assigned to the variable

User variables in the front plus one "$" symbol, so that variable names are replaced by variable values. Bsh variable conditions can be replaced, which occurs only when certain conditions be replaced. Replace the conditions on a pair of braces (), such as:

$ (Variable:-value) variable is a variable value, value is a variable substitution using the default values

$ Echo Hello $ UNAME
The results showed: Hello
$ Echo Hello $ (UNAME:-there)
The results showed: Hello there
$ Echo $ UNAME
The results showed that: (empty)
$ UNAME = John
$ Echo Hello $ (UNAME:-there)
The results showed: Hello John

Can be seen, variable substitution using the command line when defined default value, but value of the variable has not changed. Another approach is to replace not only replace the default values, and the default value is assigned to the variable. The form:

$ (Variable: = value)

The form also the value of the variable value after replacement of character to the variable variable.

$ Echo Hello $ UNAME
The results showed: Hello
$ Echo Hello $ (UNAME: = there)
The results showed: Hello there
$ Echo $ UNAME
The results showed that: there
$ UNAME = John
$ Echo Hello $ (UNAME:-there)
The results showed: Hello John

Replacement value of the variable can also be enclosed in `` command:

$ USERDIR = ($ Mydir: - `pwd`)

Replace the third variable is assigned only when the variables are replaced only when the form with the specified value:

$ (Variable: + value)

Only the variable variable has been assigned, its value was replaced with the value, or without any replacement, for example:

$ ERROPT = A
$ Echo $ (ERROPT: + "Error tracking is acitive")
The results showed: Error tracking is acitive
$ ERROPT =
$ Echo $ (ERROPT: + "Error tracking is acitive")
The results showed that: (empty)

We can also use the error checking of the conditions of variable substitution:

$ (Variable:? Message)

When the variable variable is set, the normal replacement. Otherwise the message will be sent to the standard error message output (if this replacement procedure appears in the shell, then the program will terminate). For example:

$ UNAME =
$ Echo $ (UNAME:? "UNAME HAS NOT BEEN SET")
The results showed that: UNAME HAS NOT BEEN SET

$ UNAME = Stephanie
$ Echo $ (UNAME:? "UNAME HAS NOT BEEN SET")

The results show: Stephanie
When the message is not specified when, shell will display a default message, such as:

$ UNAME =
$ Echo $ (UNAME:?)
The results showed that: sh: UNAME: parameter null or not set

4> location variable or Shell parameters

In the shell interpretation of the user's command, will command the first word as a command, while the other characters as a parameter. When the command corresponding to the executable file for the Shell process, these parameters will serve as the location of the variable passed to the program. The first parameter is recorded as $ 1, the second for $ 2 to $ 9 .... the ninth. 1 to 9 which is the real parameter name, "$" symbol is used to identify variable replacement.

Location corresponding to the variable $ 0 refers to the command executable file name. Described in detail later position in the variable.

1. Read-only variable

Users after the variable assignment, in order to prevent future changes to the variables, you can use the following command the variable is set to read-only variables:

readonly variable

2.export command

shell execute a program, the first for the program to establish a new execution environment, called the sub-shell. Variable in the Bourne Shell is local, that is, they only create them in a meaningful Shell. Users can use the export command to variables identified by other sub-Shell. However, it is impossible for a user variable for other users.

When a user starts a new shell, the shell will use the default prompt. Because the value assigned to the variable PS1 effectively only in the current shell. In order for children to use the current Shell Shell defined prompt, you can use the export command:

$ PS1 = "Enter command:"
Enter command: export PS1
Enter command: sh
Enter command:

At this point the variable PS1 into a global variable. It can be used by its sub-Shell. When the variable is set after the overall situation, would remain in force until the user exits the variable where the Shell. Users can file. Profile in a permanent assignment to a variable. See "Standard Shell".

Basic statement

From this section, we will detail the basic knowledge of Shell Programming, by writing Shell scripts, the user can according to their needs conditional or repeated execution order. Through the Shell program, a single UNIX command can be combined into a fully functional tools to complete the task of the user.

1> What is the Shell process

When the user in the UNIX Shell, enter a complex command, such as:

$ Ls-R / | greo myname | pg

We can call the user program in the Shell, when put the statement written in a file and breaks to the file executable permissions, then the file is what we traditionally say the Shell program.

2> Simple Shell program

The following commands assume that users use every day to back up their data files:

$ Cd / usr / icewalk; ls * | cpio-o> / dev/fd0

We can write it in a file, such as: ba.sh in:

$ Cat> ba.sh
cd / usr / icewalk
ls * | cpio-o> / dev/fd0
^ D (ctrl_d)

Shell script program ba.sh is, the user can use vi or other editing tools write more complex scripts.

At this point the user backup files only need to execute Shell program ba.sh, Shell in the current implementation needs to create a sub-Shell:

$ Sh ba.sh

When the user login process sh Bourne Shell executed the same command but with parameters ba.sh Sh, it will no longer be an interactive Shell, but to read directly from the file ba.sh command.

Executive ba.sh another way in order to file ba.sh execute permissions:

$ Chmod + x ba.sh

At this point, the user can enter the file name ba.sh as a command to back up their data, to note that in this way to execute commands when the file ba.sh must exist in $ PATH environment variable to the path specified on.
  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

Related Posts of Under unix shell programming (1)

  • Mantis maintenance project summary

    Maintaining the company's recent Mantis, done several times before adjustment, are different, this project obviously nervous than ever. Projects, but in the small projects I learned a lot through it I can clearly feel an even bigger "under high p

  • Rails authentication system plug-ins: Restful Authentication

    Brief introduction Restful Authentication plugin for you to generate a REST-style authentication system template, apart from support for basic user management and authentication functions, have an optional e-mail activation. Author: Rick Olson Licens ...

  • Software production and model: separation of the field

    ps: this book is strong theoretically, just start over a few chapters on the embarrassment, and now use the turn out really feel kind of realized, one by one to record Communicate at the domain model, the model discussed at the exchange in the genera ...

  • ror opensource project open source rails application

    warehouse management http://www.warehouseapp.com/ version Boxroom sharing and managing files online online document management and sharing application http://boxroom.rubyforge.org/ Osirails. With a small-scale ERP systems including some ERP features ...

  • Java Products and software download

    This column provides hundreds of Java products and software download site link and brief introduction developerWorks Web site resources related technologies. Through this column, you can easily find you need Java tools, components and code, but also can v

  • Ten most widely Javascript framework

    Reprint: CSDN Recently, the well-known technology development SYS-CON Media website lists the ten most widely Javascript framework, the article said, Javascript library has become a basic site design excellence, today almost all sites with Javascript or A

  • Tutorial on ruby-debug

    Posted on July 11, 2006 Installation The installation procedure requires rubygems package and C compiler available. Two notes worth to mention: For Debian users, you must have ruby-dev package installed. For Windows users, I don't have a precompiled v

  • What is a rake and rake command brief introduction

    Rake (http://rake.rubyforge.org) are to build a language, and make (www.gnu.org/software/make/) ant (http://ant.apache.org) is to imagine. Rake is written in Ruby, it supported its own DSL to handle and maintain Ruby applications. Rails using rake ex ...

  • Subject: rake and rake command what is brief introduction

    http://www.javaeye.com/topic/300375 Rake (http://rake.rubyforge.org) are to build a language, and make (www.gnu.org/software/make/) ant (http://ant.apache.org) is to imagine. Rake is written in Ruby, it supported its own DSL to handle and maintain Ru ...

  • Sign in spring struts2.0 hibernate user authentication

    Engage in a day has finally put the ghost of a user log in to engage in things out. . Ah first experience with a spring to manage the bean is a good tool. Of course, far more than this spring profound role in it. This is called a simple sense of the ...

blog comments powered by Disqus
Recent
Recent Entries
Tag Cloud
Random Entries