Linux Shell Introduction

Source: http://www.linuxsir.org/main/?q=node/135

Linux Shell Introduction



Original: http://www.mandrakeuser.org/doc
Chinese translation: Wu Xiaoguang http://dummy.linux.net.cn/ ~ xgwu / cmuo /
Order: flaboy North South North
Comments: flaboy brother was made in the LinuxSir.Org when finishing SHELL discussion forum area, "Linux Shell Introduction" , is based on material in the form of a quote out of his finishing time "this compilation of relevant sections of sorting to do when the corresponding The deletion processing, removing part for Mandrake Linux. ";

I read this document very well, finishing once again carried out, and structure of the document have been adjusted the content of the document, plus I have the serial number right, and made a directory, mainly facilitate perusal; thank original authors and the translator, but also thanks flaboy brother of the order;

Copyright Information

This content comes from the MUO the Basics section, the original English version can be obtained from here http://www.mandrakeuser.org/docs . Chinese from the heating intensity of CMUO http://dummy.linux.net.cn/ ~ xgwu / cmuo / . MUO is Mandrake Linux (http://www.mandrakelinux.com/) entry for the user manual, practical and real-time updates of its content is suitable for beginners to do entry-reference. With the common variety of different Linux tutorials, MUO introduced to Linux for beginners to learn Linux on a system approach rather than a description, which all have a vastly different Linux distributions the study is particularly important.

This compilation order made when the relevant sections of the corresponding deletion processing, removing part for Mandrake Linux.

Introduction <br /> use Shell

The following will introduce and explain the basic shell commands and mechanisms.

First: super tools / Terminals, xterms, and Shells


First, super tool


You may have heard this argument: the command line (the mommand line) has long been obsolete, that mystery of things, and so on. Some people even think that the operating system should not have these commands we go.

The fact is, you can not understand any shell, will be able to use Linux. After you start the system direct access to X Window, the last under the X Window Shutdown.
I firmly believe that with Linux and no shell, like a car will use the header files (first gear) the same. Of course, the first seems simple and straightforward, in most cases, use it. But slower, and can not really experience the driving pleasure.

Yes, the command line is very interesting. Collected as building blocks with a lot to him, to complete a number of unexpected initiative, some extremely complex task, just a few lines of command can be resolved. This is because in Unix in, shell is not a simple command interpreter (typically Windows, DOS), but a full-featured programming environment.
This does not mean that shell is easy to learn through, you know, sometime this is something to take. ;-) But please believe me, this is definitely worth. You are in a very short period of time, a bunch of amateurs can be touted as a Unix wizard (Wizards). * Grin *

Second, to illustrate the shell, here need some background knowledge.


1, Terminals, xterms and Shells


Dating back to the birth of that time Unix was not now popular "personal computer." Known as the computer's machine, or handling the tape and the magnetic memory (using the term 'core' to represent the system memory) of the monster. DEC (now Compaq) introduced PDP-11, small size (called mini) and the price of the end of the university caused a huge response, many schools can afford to buy until then a computer (PDP-11 inexpensive, only $ 10,000).

The machine's operating system by the assembly language, machine language written in, so run up and efficient, but they can not transplant (unportable). Each computer companies gave their machines coupled with a unique operating system, and then sales.

This clumsy approach was recognized as quickly, so he began to build a brand in different operating systems running on the machine. In 1969, Ken Thompson became the Unix began writing the first lines of code. (Thompson had participated in a project: MULTICS, Unix is a joke that the word) In fact, Dennis Ritchie designed for the new operating system, a new programming language - C language, things really started.

Although the efficiency is less than the original Unix operating system, but there are three outstanding advantages: can be ported to any other machines, one of the C language the programming easier, but these are free. Soon, all U.S. universities are busy start for the machine to install Unix.

2, terminal (Terminals)


Unix machines can run on many kinds of operating systems, but how people use these machines? They are through dumb terminals connected to these machines, that is, keyboard, monitor and enough electronics (electronic components) consisting of machines with a central computer (central computer) connected. In the end, the user can knock characters (teletypy), this is the string 'tty' said terminal device file, and 'getty' command name origin.

You may ask, Where are all these things now. The manufacturers of these devices can not reach a final standard, which led to the termination of each brand has its own keyboard layout, each character in the screen means to send or receive any signal that what characters, control code and so on.

To avoid such confusion, it creates a terminal with all the different features (capability) file, this is the 'termcap'. With a tool to open '/ etc / termcap' Look, do not scare the ;-).

Most Linux terminal with 'vt100' or 'linux' as the terminal type.

3, xterms


In the early eighties, resulting in a Unix graphics subsystem - the X Window System. The early nineties, in order to better realize the Intel-based Unix-type systems (such as FreeBSD, NetBSD, Linux) application, created a system branch - XFree86.

X Window is a great advantage can run multiple virtual (virtual) terminal. Even under the X Window applications have such a - 'xterm'. You will find 'xterm' and 'virtual terminal' in many cases are the same. Some places say, 'Open a xterm', in fact you do not insist with the 'xterm' program, the other terminal emulator (terminal emulator), such as rxvt, konsole, aterm, eterm, wterm so as effective.

Terminal emulator (also known as virtual terminal) through the pseudo (pseudo) tty device - pty connected to the system, and use their own display standard - xterm. This leads to a different terminal emulator or procedures may exist a number of key differences between small, depending on the extent to which compliance with the emulator 'xterm' display criteria.

4, Shells


To run the program in the terminal needs to shell. part of the operating system shell is used to dealing with users, and can be used to coordinate the various commands.

The first real Unix shell - 'sh', also known as the 'Bourne shell', was born in 1975, the author is Steve Bourne. Soon, there are other shell, such as on the original 'Bourne shell' of the 'ksh', 'zsh', which is often used as a standard proprietary Unixes system shell; also some derived from the C language in the shell, such as' csh 'or' tcsh '.

In Linux, the shell is marked 'bash', that is the GNU Bourne-Again Shell (a little taste of a joke ... ...). The shell is very powerful (and even some people feel too large), compressed man page there is 50 KB.

3, Shell started


First, there is little explanation: the usual applications, we recommend that you do not use 'root' account to run shell, if you are still new to this particular attention. As an ordinary user, whether you intentionally or unintentionally, can damage the system; but if it is 'root', it is different, just knock on a few letters, it could lead to disastrous consequences.

When you login or open an xterm window first to see the prompt (prompt). Red Hat Linux standard prompt includes your user name, sign the host name (not set, then, is 'localhost'), the current location of the directory (working directory), prompt:

[tom@belbo tom]$

I have a user name 'tom' login name 'belbo' host, the current in my home directory - '/ home / tom' in. 'Root' of the prompt:

[root@belbo root]#

In addition to a different user name, the prompt from the '$' into a '#'. According to the traditional Bourne shell, common user prompt to '$' end, while the super-user with a '#'.

Prompt can be customized for each part, you will have a deeper understanding of the back.

To run the command, you simply knocked into the command prompt, and then in the button. shell in its path (see later) Search this command to find later on the run, and the output terminal corresponding results (if any), after the command, and then given a new prompt:

[tom@belbo tom]$ whoami
tom
[tom@belbo tom]$


Incidentally, that when you hit ENTER, the cursor (cursor) where does not matter, because the shell always to read the entire line.

Basic commands are: 'ls' (list directory, list directory contents), 'cp' (copy, copy), 'mv' (move / rename, move / rename), 'cd' (change directory, change directory ), these commands can be followed to keep up with a bunch of options, this man page with detailed description (man ls, man mv, etc.).
Shell in your left for territory before, here are a few terms (terminology) a brief description. Command may take a number of options (options), parameters (arguments):

mv -i file dir

Where '-i' is the command 'mv' of an option, and 'file' and 'dir' is a parameter. All available options in the order of the man page describes in detail all (in this case using man mv), and parameters from you. Option to decide how the work can command, and parameter command is used to determine the role of the target.

So far, introducing a little too lightly, as many people dislike the DOS shell, but with the following description, you will have a new experience.


Second: Auto padded / command-line history / edit the command line / shortcuts available to Shell


Unix (and successor to Linux) the command line following the birth, therefore, Unix's command line has many very useful features. In this, we have some understanding of the future.

1, auto filled;


How to use the 'cd' (change directory, change directory) the fastest way from your home directory where the current jump '/ usr / src / redhat /' do?

cd /u<TAB>sr<TAB>r<TAB>

This is called 'command-line automatically append' (automatic command line completion), which in ordinary applications is essential. Let us look at this example:

cd /u<TAB>

Expansion into cd / usr /, it is very simple. The following

cd /u<TAB>sr<TAB>

Extended cd / usr / src /. If you only knock on the cd / us, '/ usr' next match ('cd / u * / s *') three subdirectories will be listed for you to choose: '/ usr / sbin', '/ usr / share' and '/ usr / src'.

Therefore, the key can easily be used according to the first few letters to find the matching files or subdirectories. For example, ls / usr / bin / zip to list all the '/ usr / bin' Now, with the string 'zip' at the beginning of the file or subdirectory. Of course, this kind of task has a more powerful command, but this method is very useful indeed.

In addition, long file name encountered is especially convenient when. Suppose you want to install a file called 'boomshakalakwhizbang-4.6.4.5-i586.rpm' of the RPM package, you type rpm-i boom, if the directory is not able to match other files, it will automatically help padded shell.

cd /usrl


Will expand into a cd / usr / src / linux, and wait to continue. '/ Usr / src' directory, there are two matching: '/ usr/src/linux- [...]','/ usr / src / linux'. How to tell the shell that you want to do later? Only with a slash (/, slash), you can choose the back too much.

If you are not sure that '/ usr / src / linux / Documentation' or '/ usr / src / linux / documentation'. And you know, Linux is case sensitive. If you have carefully read the previous section, then you can think of:

cd /usrl/d


Expanded into '/ usr / src / linux / drivers /', so should be 'Documentation' (uppercase 'D').

This padded on the command also works:

[tom@belbo tom]$ gre<TAB>

grecord grefer grep

[tom@belbo tom]$ gre


Here shell will list all the string 'gre' at the beginning of the known commands.

Second, the history of the command line


By pressing the up arrow keys, you can traverse back recently in the console, enter the command. Down arrow keys to move forward with the traversal. With the SHIFT key terms together, you can traverse in the past in the console output. You can also edit old command, and then run.

By post, shell enters the "reverse-i (ncremental)-search" (backward incremental search) mode. Now enter the command you're looking for the first letter:

(Reverse-i-search )`':. Knockin 'i' may become:

(Reverse-i-search) `i ': isdnctrl hangup ippp0

If you re-key, the above command will be executed again. If you press the right, left arrow keys or the above command will return to normal command line, so you can properly edit.

Edit the command line

Through the cursor and function keys (Home, End keys, etc.), you can browse and edit the command line, if you need, you can also use the keyboard shortcut to complete the general editor:

l <CTRL k>: Delete from cursor to end of the line section
l <CTRL u>: Delete from cursor to the start of the line section
l <ALT d>: Delete from cursor to end of the current part of the word
l <CTRL w>: Delete from cursor to the current part of the beginning of Word
l <CTRL a>: Move the cursor to the beginning of the line
l <CTRL e>: Move the cursor to the end of the line
l <ALT a>: Move the cursor to the current word head
l <ALT e>: Move the cursor to the end of the current Word
l <CTRL y>: Insert the recently deleted words
l <!$>: Repeating the previous command last parameter .


For example: You use the command mkdir peter / pan / documents / tinkerbell created a new directory, and now your users with a command 'cd' into the directory, you can use cd! $, Shell before the command will 'mkdir' parameters to Now 'cd' back.

When you a better understanding of Linux, will see the shortcuts in other applications, enter the time, sometimes effective, for example, in the browser in the input box.

Third, the available shortcuts Shell


Red Hat Linux with a lot of shortcuts, in which there is a part of the original bash while some are pre-set for you (in the back you will see how to set up).

As the home directory is the center of each user's activities, many of Unix have a special shortcut.

'~' Is shorthand for your home directory form. We assume you are in other directories, wanted a name 'sometext' the files to your home directory 'docs' subdirectory. In addition to input:

cp sometext /home/myusername/docs

You can also use the shorthand:

cp sometext ~/docs

Theoretically, this can also be used in the command 'cd' on. No matter where the current path, cd ~ will return to your home directory. In fact, can also be simplified, just type cd, you can return home a directory.

Red Hat Linux to provide you with some pre-set shortcuts (called 'aliases', aliases), such as:

l ll : Will perform a 'ls -l -k'( To list directory contents in long format, including some of the attributes of a file , And with a KB instead of byte Display file size )

l ls : Will perform a 'ls -F --color=auto'( Lists the directory contents, plus the files of type ID , Using color )


You should now be on the shell and some shortcuts have a better understanding, let's take a look at in addition to apply some simple commands, shell can be anything.

Part III: Command of the arrangement / order of the task scheduler / command replacement


1, arranged in order


Now you will see some common command arrangement. You may want to give all the commands in a row, you can then turn its attention elsewhere. No problem, shell allows you to order different between, put a special arrangement of characters (queuing characters). Here will introduce the two most commonly used.

Note that, in order to look more clear, I added a space on both sides of these characters. In practice, you may not want to do this, 'ls-a; du-hs' and 'ls-a; du-hs' effect is the same.

command1 ; command2

First implementation of command1, regardless of command1 is wrong, then the implementation of command2.

For example:

ls -a ; du -hs

Will be listed first on the screen the entire contents of the directory, then list all the directory and its subdirectories share of disk size.

command1 && command2

Only if command1 properly completed before the implementation of command2.

For example:

ls -a bogusdir && du -hs

Will return ls: bogusdir: No such file or directory, while 'du' is not running (this is because you do not 'bogusdir' directory). If you sign replaced';',' du 'will be executed.

For further information ';' and '& &' distinction, and the general usefulness of the command arrangement, a classic example of the following cite: Linux kernel compiled and installed.

To compile, install Linux, you need to perform a string of commands: 'make dep', 'make clean', 'make bzImage', 'make modules', 'make modules_install' and 'make install'. If you have to wait for the completion of a command, then enter the next one, wait, then enter, ... ..., it is too cumbersome. On the other hand, only the current surface of each command are correctly after the command to begin. If you use ';' to arrange the order, even if the command fails, the back has to run as usual, and finally, you may be '/ boot' directory, get a kernel image problem (image). The use of'&&':

make dep && make clean && make bzImage && make modules && make modules_install && make install

Do not interrupt, you can compile the kernel and its modules, and complete the installation of the back.

Second, the command of Task Scheduling


When you run a command in a terminal or open a program, the terminal to wait until after the command or program to run, can be used again. In Unix, we call such a command or program in the foreground (foreground) run. If you want to run another command in the terminal, you need to open a new terminal.

But here there is a more elegant approach, called task scheduling (jobbing) or background (backgrounding). When you use the task scheduler or the command placed in the background, the terminal immediately liberated, and this way, the terminal immediately able to accept new input. To achieve this purpose, you simply add an & after the command:

gqview &

Tell shell to picture viewer 'GQview' into the background to perform (that is, to run as a job).

Command jobs will tell you, in the terminal window, run the commands and procedures which:

jobs

[1]+ Running gqview &


When you want to close the terminal window, it is important, because the closure of the terminal will cause all running tasks which will be suspended, in this case, if you close the terminal from the terminal will open GQview procedures was closed.

But how to run a program into the foreground to the background? No problem:

gqview

<CTRL z>

[2]+ Stopped gqview

bg

[2]+ gqview &


Combination of keys will hang the terminal is running, then you can use the bg command to put the background to do it.

Please note that graphics applications running in the background is sometimes useful, so that the terminal can display an error message of this process, although you may not directly help, as if run into trouble, the others asked, these an error message comes into play.

Some graphics programs, are likely still in the testing phase (Beta), although in the background, it will also output some information in the terminal. If you are dissatisfied, you can use the following command:

command &>/dev/null &

This will not only send back the implementation process, the output will be sent to '/ dev / null' file. '/ Dev / null' is the system of "shredders" (shredder), where all information will be sent to disappear.

Third, command replacement


Command substitution (Command substitution) is a very useful function. We assume that you want to see XFree86 documentation 'README.mouse' file, but you do not know the location of the file. But you is a clever users have heard of 'locate' command, also installed the 'slocate' package, you can use:

locate README.mouse

Found that file in '/ usr/X11R6/lib/X11/doc'. Now you can use in a terminal 'less' or the file manager and then read the file into that directory. The command substitution can bring some convenience to you:

less $(locate README.mouse)

Step. Command 'locate README.mouse' output (= / usr/X11R6/lib/X11/doc/README.mouse) as 'less' of the parameters, then you can display the file content.

The syntax of this mechanism are:

command1 $(command2)

In addition to '$ ()', you can also use the following quotes (backquote):

command1 `command2`

Although this can reduce the input, but the readability is poor, and very easy and does not replace the function of the general confusion single quotation marks. I appreciate the former method, but in the final decision to you.

Here is another example. We assume that you intend to end a called 'rob' the program. You come with the command 'pidof' to find the appropriate process ID (Process ID), then the PID as a parameter, run 'kill' command, so that an end to 'rob' program. In addition to using:

pidof rob

567

kill 567


You can also try:

kill `pidof rob`

How, efficiency has increased, right?

The next one, I will then introduce two other shell practical mechanisms: file name matching, output redirection.

Part IV: file name matching / output redirection


First, the file name matched


File name so you do not have 11 matches to write the name, you can specify multiple files. You will use some special characters, known as the wildcard (wildcards).

Suppose you want to use 'rm' command to delete all directories under the string '. Bak' at the end of the file. In addition to 'rm' to keep up with all the files after the name as a parameter, you can also use the wildcard '*':

rm *.bak

'*' Can match one or more characters. In this case, you tell the shell command 'rm' parameter extended to "all to '*. bak' end of file", shell parameters will be expanded to tell 'rm' command.

You will see, shell before the command execution, will read and interpret the command line. Because of this, you can be a wildcard for the shell command of the parameters.

Allow us to further understand wildcard '*'. Assuming you have a catalog, which contains files '124. Bak ', '346. Bak' and '583. Bak '. You want to keep only file '583. Bak ', you can use:

rm *4*.bak

shell will be '* 4 *. bak' extension into the "all with '4 'and to'. bak 'at the end of the string."

Noting rm 4 *. bak not work, because this match is '4 'at the beginning of the file. Because there is no such file directory, shell will expand the model to the empty string, so 'rm' will return an error message:

rm: cannot remove `4*.bak': No such file or directory

If you want to keep file '345. Bak ', and delete '124. Bak' and '583. Bak '. It may seem difficult, because the deleted file names in addition to other suffix is different. Fortunately, you can use to specify the file does not contain:

rm *[!6].bak

This will be read as: In addition to the '6. Bak 'at the end of the file, delete all to'. Bak 'at the end of the file. No. You have to take anti-(negation sign) and take anti-character (in this case 6) into the brackets, otherwise, shell will be an exclamation point (exclamation mark) interpreted as the beginning of history, replaced (the beginning of a history substitution) . No. negation introduced in this model are valid for all matches.

Please note: wildcard '*' and take anti-number used together can easily create problems. Guess

rm *[!6]*.bak

Does that mean? This command will delete all the files, and even the name contains '6 'files. If you wildcard '*' put a check in front of and behind the counter number, in fact, the failure to take anti-number, because shell be interpreted as "all the names in any position of the character of the file are free." In our case, the only file '666. Bak 'does not match the pattern.

The second wildcard is the question mark (question mark ):'?'. In the match, a question mark can represent only one character. In order to demonstrate its use, the assumptions in the above example we add two new files: '311. Bak ~ 'and' some.text '. Now, list all the four characters after the dot file:

ls *.????

Question mark wildcard can effectively avoid the above-mentioned 'take anti-trap No.' (negation trap):

rm *[!4]?.*

Will be extended to "all but the penultimate one before the dot character to '4 'document" that is, retaining only file '346. Bak'.

You may ask, are there other matching? So far, you only see the only character in the specified location matching method. But in fact you can do:

ls [13]*

Will list all the characters '1 'or '3' at the beginning of the file; In our example, the file '124. Bak ', '311. Bak ~' and '346. Bak 'match. Notice that you must use brackets to enclose the pattern matching, or pattern match only a string '13 'at the beginning of the file.

Next, you will be pleased to see that can match the scope of the definition:

ls *[3-8]?.*

Will list all the dots before the character falls on the penultimate '3 'to '8' range of documents. In our example, the matching file is '346. Bak 'and '583. Bak'.

Second, the reference shell special characters


However, the above there is a drawback to those mechanisms: shell always in command before, try to be extended. Sometimes, a bit more tricky:

l The file name contains special characters. Suppose you in that directory also has a class named '!56.bak' File-following the attempted pattern matching :
rm !*
rm
rm: too few arguments


shell will be '! *' interpreted as history substitution (adding a command before all parameters), rather than matching.

l command itself with a special character as a parameter. Linux command line under a number of tools, such as (e) grep, sed, awk, find and locate, use your own regular expressions (regular expressions). These expressions and pattern matching look strikingly similar, but different in some places there.

However, in order to force these special commands, shell can not be his first match as a model to explain:

find . -name [1-9]* -print
find: paths must precede expression


Should be:

find . -name '[1-9]*' -print
./346.bak
./124.bak
./583.bak

./311.bak~


You can use a backslash (back slash) to refer to special characters such as!, $,? Or spaces:

ls \!*

!56.bak


Or, (single) quotation marks:

ls '!'*

!56.bak


Please note that quotation marks should be placed to look at what position. Command ls '! *' Will find the name '! *' The file, this is because the wildcard are between quotation marks, it can only be interpreted in accordance with the letter.

Third, the output redirection


Unix philosophy is to bring together many small programs, each stuff has a special expertise. Complex task is not completed by the large-scale software, but use shell mechanism, a common combination of many small programs to complete. Redirect to play a significant role.

1, in a number of command between the redirection


This should be through a pipe (pipe), by the pipe symbol | to identify. The syntax is:

command1 | command2 | command3 And so on

You must have seen this format before. Pipe output of one program often send 'more' or 'less' to read.

ls -l | less

One, the first command provides tables of contents, the second will be to flip the way of its display. More complex examples such as:

rpm -qa | grep ^x | less

The first command shows all installed RPM packages, and the second will be the filter (filter: 'grep'), only to '^ x' at the beginning of the package, the third command will result in turning the pages displayed.


2, redirect to file


Sometimes, you want to save the command output to a file, or file content as a command parameter. This can be '>' and '<' "to achieve.

command > file

The command's output saved to file, this will overwrite file contents:

ls > dirlist

Save the current contents of the directory to the 'dirlist' file.

command < file

The file contents as a command input:

sort < dirlist > sdirlist

The file 'dirlist' content sent to the command 'sort', and then sort the results sent to the file after the 'sdirlist'. Of course, you can step:

ls | sort > sdirlist

A special way 'command 2> file'. This command executed in the error message sent to the file. This time will need you to ... ...

Another operator is'>>', this will add to an existing output file:

echo "string" >> file

Add file file in the string. This is not open the file and a good way to finish editing!

However, the '<' "and '>' operator has an important limitation:

command < file1 > file1

Will delete the contents of file1, while

command < file1 >> file1

They can work very well, the processed content added back to the file file1.

Is not it a little more? ;-) Do not panic, you can own pace, step by step to learn. Do not forget, practice is the best way to learn ... ...

Many well-known mechanism of shell, you may want to know how to customize the anxious environment. In the following two, you will receive this revelation. In the final paper, the there is still a shell error messages how to deal with frequently asked questions (FAQ), and some configuration tips.

Fifth Article: bash configuration file / prompt / change $ PATH


1, bash profile


In your home directory, run

ls .bash*

You will see these files:

l .bash_history : Record the settings that you previously entered commands ,

l .bash_logout : When you exit the shell , The command to perform ,

l .bash_profile : When you login shell , The command to perform ,

l .bashrc : Each time you open a new shell , The command to perform .


Please note that the difference between the latter two: '. Bash_profile' is only the beginning of the session is read once, but '. Bashrc' then every time you open a new terminal (such as a new xterm window), they must be read. According to tradition, you have to define the variables such as PATH, put '. Bash_profile', rather like the aliases (alias) and the function of the class, then on '. Bashrc'. However, since '. Bash_profile' is often set to the first read '. Bashrc' content, if you the easy way out, then put all the configurations are put '. Bashrc'.

These files are each user's settings. System-level settings are stored in '/ etc / profile', '/ etc / bashrc' and the directory '/ etc / profile.d' under the file. But you get used to using their own configuration file: editing does not require 'root' privileges, you can make your set more personal. When the system level and user level settings conflict, will use the user's settings.

Read '. Bashrc' content, if you want to save some things, put all of your configurations into the '. Bashrc'.

These files are the above settings for each user, system-level settings are stored in '/ etc / profile', '/ etc / bashrc' and the directory '/ etc / profile.d' under the file. You better get used to using their own configuration file: editing does not require 'root' privileges, but also can personalize your settings. When the system level and user level settings conflict, priority will be given by the user's settings.

Second, prompt


Each time you open a console (console) or xterm, the first to see is prompt (prompt), similar to:

account@hostname ~ $

In the default setting, the prompt will display your user name, host name (default is 'localhost'), the current directory (in Unix, the '~' means your home directory).

According to tradition, the last character to identify your ordinary user ($), or 'root'(#).

You can set the prompt variable $ PS1. Command

echo $PS1

Will display the current settings. In which the meaning of the characters available in the man bash the 'PROMPTING' part of a description.

How to complete the ideal setting it? For the forgetful beginners speaking, the default setting that some unfriendly, because the prompt shows only the last part of the current directory. If you see a prompt like this

tom@localhost bin $

Your current directory may be '/ bin', '/ usr / bin', '/ usr / local / bin' and '/ usr/X11R6/bin'. Of course, you can use

pwd (output current directory, print working directory)

Called the shell can automatically tell you what the current directory?

Certainly. Here I will refer to the set, including the prompt, mostly contained in the file '/ etc / bashrc' in. You can edit their own home directory '. Bash_profile' and '. Bashrc' to change the settings.

In the man bash in the 'PROMPTING' part, on these parameters (parameter) is described in detail. You can add some gadgets, such as different formats of the current time, the command history number, or even different colors.

In the '~ /. Bashrc', I like the setting is:

PS1="\[\033[1m\][\w]\[\033[0m\] "

'Root' in '~ /. Bashrc' in the set are:

PS1="\[\033[0;31m\][\w]\[\033[0m\] "

I got a prompt that is:

[/usr/bin]

When using 'root' when, becomes:

[/usr/bin]

I have removed the host name and user name, because I do not need these. But I would like to see my identity at a glance an ordinary user or 'root'. Noted that normal users can prompt black and white, or black and white.

To get the right color terminal deployment, you can edit the following script color, to give execute permissions (chmod + x color), and then run.

#!/bin/bash

#

# This file echoes a bunch of color codes to the

# terminal to demonstrate what's available. Each

# line is the color code of one forground color,

# out of 17 (default + 16 escapes), followed by a

# test use of that color on all nine background

# colors (default + 8 escapes).

#

T='gYw' # The test text

echo -e "\n 40m 41m 42m 43m\

44m 45m 46m 47m";

for FGs in ' m' ' 1m' ' 30m' '1;30m' ' 31m' '1;31m' ' 32m' \

'1;32m' ' 33m' '1;33m' ' 34m' '1;34m' ' 35m' '1;35m' \

' 36m' '1;36m' ' 37m' '1;37m';

do FG=${FGs// /}

echo -en " $FGs \033[$FG $T "

for BG in 40m 41m 42m 43m 44m 45m 46m 47m;

do echo -en "$EINS \033[$FG\033[$BG $T \033[0m";

done

echo;

done

echo


A more appropriate setting:

PS1="\u: \w\\$ "

Thus, prompt becomes:

user_name: /usr/bin$

You can export order to test different settings (eg, export PS1 = "\ u: \ w \ \ $"). If you find the appropriate prompt, it will be set into your '. Bashrc''in. In this way, each time you open the console or terminal window, will take effect.

You can even set to prompt the theme (theme), that is, with different colors, it looks like a great ol
The C64 prompt. If you are interested, you can look at
Bashish (http://hem.passagen.se/arnognulf/index2.html).

Third, changing the $ PATH


'$ PATH' and '$ PS1', just as environment variables. Enter

set

Will list all currently defined environment variables.

You can see the environment variables defined in the profile shell, may be user profile may be created by 'root' via '/ etc' following systems-level document definitions. If you use X, more number of variables will be X, your window manager or desktop environment startup file configuration.

If these settings are not very clear, you'd better not arbitrarily change the time being. Learn how to change the $ PATH variable is useful because this variable determines the shell to which directory to find the command or program. To run the command directory in $ PATH, you do not need to enter the full path to this command, enter the command on it. Some third-party software not executable files on a standard Linux directory. Therefore, these non-standard installation directory to $ PATH is a solution. In addition, you will see how to deal with the general environment variables.

First of all, as a rule, all environment variable names are capitalized. Since Linux is case-sensitive, this point you want to watch. Certainly, you can define your variables, like '$ path', '$ pAtH', but the shell does not ignore these variables.

The second point is that sometimes the variable name with '$' at the beginning, but sometimes not. When setting a variable, you use the name directly, without the need for additional '$':

PATH=/usr/bin:/bin:/usr/local/bin:/usr/X11R6/bin

To obtain the variable value, then we will have the variable names with '$':

echo $PATH

/usr/bin:/bin:/usr/local/bin:/usr/X11R6/bin


Otherwise, the variable names will be treated as ordinary text of the:

echo PATH

PATH


$ PATH variable handling third point to note is: you can not just replace the variables, but to add a new string to the original value. In most cases, you can not use the 'PATH = / some / directory', because it would remove the $ PATH of all the other directories, so you run the program in the terminal, will have to give the full path. Therefore, only for add:

PATH=$PATH:/some/directory

This, PATH is set to the current value (in $ PATH to that) + Updates to the directory.

So far, you only for the current terminal set a new $ PATH variable. If you open a new terminal, run the echo $ PATH, will return to the old value of $ PATH, but not the new directory you just added. Because you previously defined a local environment variable (limited to the current terminal).

To define a global variable, so in effect after the terminal opened, you will need local variable output (export), can 'export' command:

export PATH=$PATH:/some/directory

Now if you open a new terminal, type echo $ PATH, also see the new $ PATH set up. Please note that the command 'export' can only be changed after the current terminal and run the terminal variables. The terminal has no effect on running.

To permanently add the directory to your $ PATH, as long as the 'export' of that line to your '. Bash_profile' file.

Please do not '. Bashrc' Set PATH, otherwise it will lead to unexpected growth in PATH in the directory. Every time you open a new shell, '. Bashrc' will function. Therefore, if you add a directory of the file each time you open a terminal, the directory will also been added. This will lead to PATH variable as directory replication, continues to grow.

Part VI: command aliases, Shell function / from here / Shell FAQ


1, the command alias, Shell function


Remember that all commands and the built-in option, and then every 11 input, this is indeed a bit boring. Fortunately, you can define shortcuts for commonly used commands. These shortcuts can be relatively simple command alias (alias), or complex syntax of some of the shell function defined.

1, the command alias


For example, I use the following command to upload the file MUO:

rsync -e ssh -z -t -r -vv --progress /home/tom/web/muo/rsmuo/docs muo:/www/mandrakeuser/docs

Obviously, if every time one by one input, then I will sooner or later turn into the wood. So I '~ /. Bashrc' alias defined:

alias upmuo='rsync -e ssh -z -t -r -vv --progress /home/tom/web/muo/rsmuo/docs muo:/www/mandrakeuser/docs'

Now, I can be completed as long as the input upmuo upload task.

The syntax for the definition of an alias is:

alias shortcut='command'

Order in space, then you need to use quotation marks (as in command and can have spaces between options). Please note that you can use single quotes or double quotes, but they are different.

Single quotation marks will be deprived of one of the special meaning of all the characters, while the double quotes in the '$' (parameter substitution), and '`' (command substitution) is an exception. This means that if you want to apply the alias variable or command substitution, you have to use double quotation marks. Look at the example above, I '. Bashrc' defines a variable called MUOHOME:

export MUOHOME=$HOME/web/muo/rsmuo/docs

In the above alias to the variable use of the word, I must use double quotes:

alias upmuo="rsync -e ssh -z -t -r -vv --progress $MUOHOME muo:/www/mandrakeuser/docs"

Otherwise, alias will find a file named '$ MUOHOME' directory or file.

You can use the 'alias' in the command line to quickly create an alias, or to order into their own '~ /. Bashrc', or into the system-level '/ etc / profile.d / alias.sh' in (and in Mandrake Linux 8 the previous version, use the '/ etc / bashrc'). To delete an alias, just type: unalias alias. Alias will be listed in your system to run all defined aliases.

If you look at '~ /. Bashrc' and '/ etc / profile.d / alias.sh', you will find that the system has defined a number of aliases. You can define multiple aliases with one command. Of course, you must first confirm that the alias name of the program different from other, such as alias rm = 'ls-l' This will not work. You can enter the command line shortcuts to test. If the shell can not find the same name of the command, then you can use it as an alias.

The following alias may be useful (do not forget the quotes!):

l alias rpmq='rpm -qa | grep' : Now rpmq string it will list all the names in the string Installed RPM packages ,

l alias ls='ls -ho --color | more' :ls The pagination in color, the size of the file listed in the file to KB As the unit ,

l alias use='du --max-depth=1 | sort -n | more' :use The subdirectory by size formed, and how to paginate lists ,


Directory alias can also be removable media: alias dlm = '/ mnt / cdrom / RedHat / RPMS /'.

Note: there will be similar to the function of the alias with the same initials, such as all the directory alias to 'd' for the beginning, which helps memory.

I believe that you will use these features.


2, Shell function


Write a shell function is related to the shell script, this is outside the scope of our discussion (not in my control within ;-)). In fact, shell functions are shell scripts, but can be pre-loaded under the same shell (preload) and implementation (and in general to open a shell script at least sub-shell).

Through the shell function, you can do a lot of things that aliases can not be completed. Here is an example:

function apros() { apropos $1 | egrep -v '(3|\(n\)'; }


Defines a new command, known as the 'apros'. apros name will be the first implementation of the 'apropos name' (ie in the man page in the search command), then the output will be sent to the pipe (|), then use 'egrep' filter, excluding the first '3 'and' n 'chapter man page, this command may not have much use, but you can order 'apropos' command output.

Function allows you to function within any location, using the run-time parameters. The alias, only allowing the end of the command line put a parameter (such as in front of the alias 'rpmq').

'$ 1' is the location parameter (positional parameter), that function is the location of the first parameter identifier. And so on, there are '$ 2' and so on.

function apros() { apropos $1 | egrep -v "\($2"; }

If you do run 'apros' command:

apros name man_section_number

This command will search for the title with name of the man pages, but exclude man_section_number parts:

apros menu 3

Will search for the title with 'menu' of the man page, but excluding the third chapter (about programming). Notice that you have to quote (quote) twice, but also use double quotes:

l You must refer to the ' egrep ' search mode , This can not be misunderstood by shell .

l You must enclose them in double quotation marks, such as the second argument in order to be properly interpreted .

l You must reference the parentheses, so that 'egrep' According to literally treated with parameters .


Is not a bit mean? ;-)

treatment similar to the alias shell function: to put your '. bashrc' file, it can be permanent in effect.


Second, from here


We talked about just a beginning of the shell. Master shell script, you can do many things, such as the automation of tasks, correcting errors others script, used to customize according to your Linux system. If you plan to learn a complex programming language, that shell script is a good start, because the basic concepts are similar.

BASH Programming - Introduction HOW-TO:

http://www.ibiblio.org/mdw/HOWTO/Bash-Prog-Intro-HOWTO.html

These topics will be more in-depth, and will take you to the world of shell programming. You can then continue to read I strongly recommend the Advanced Bash-Scripting Guide (http://www.ibiblio.org/mdw/LDP/abs/html/index.html), the author is: Mendel Cooper.

If you prefer paper books, then I recommend S. Veeraraghavan's "Teach Yourself Shell Programming", Sams Publishing. I would think that O'Reilly, by the Newham / Rosenblatt written "Learning the bash Shell", so-so, but this may only I think so ;-).

In addition to these, is practice, practice, practice. Reading other people write the shell script to see what they are doing, how to do it, why not do that.

Please do not use 'root' to test your script. Have fun.

About this article

flaboy brother was when the order issued in the LinuxSir.Org forum discussion area SHELL, SHELL basic materials as a form of posts, and his finishing time "when finishing this compilation of relevant sections of corresponding changes done deal, removing part for Mandrake Linux. ";

I read this document very well, finishing once again carried out, and structure of the document have been adjusted the content of the document, plus I have the serial number right, and made a directory, mainly facilitate perusal; thank original authors and the translator, but also thanks flaboy brother of the order;

Ye Shi Xiang file papers I slip into something more happy things, at least look at the document, I can know which yes protant comparison, but also get what I want learn, so I have been finishing the document; if time permits and have the ability, I will write. ─ ─ North South North

Order without any technical content of the document is, why would you do?

Although there is no technical content, but I think if we can bring a little bit of convenience for others, I think I have done or should be, relatively original and the translator, I do what they count?

─ ─ North South North
  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

Related Posts of Linux Shell Introduction

  • Ruby Server

    sudo vi / etc / apt / sources.list deb http://mirror.pacific.net.au/linux/ubuntu/ gutsy universe restricted main multiverse deb-src http://mirror.pacific.net.au/linux/ubuntu/ gutsy universe restricted main multiverse deb http://security.ubuntu.com/ubuntu/

  • Ruby on Rails installation notes

    First, install the ruby, the first from the http://www.ruby-lang.org/zh_CN/downloads/ Ruby download the Windows version of the stability of the installation Step in the installation of Ruby 1.8.6 (md5: 00540689d1039964bc8d844b2b0c7db6) stable version (rec

  • Understanding of JavaScript closures

    Understanding of JavaScript closures To become advanced JavaScript programmers, it is necessary to understand the closure. In this paper, ECMA 262 specification explain the closure of the internal working mechanism for JavaScript programmers understanding

  • Ext project summary

    <Private http://www.javaeye.com/topic/320633> Recently, ext finally make use of a small web project. Ext used for the first time to do the project, after all, lack of experience, just write down a number of development ideas and required attention.

  • REST on Rails

    Series, the previous article said that Ruby on Rails is a sudden pop up a framework for the Ruby programming language to serve as a catalyst. With the continued success of the experience of Ruby, developers began to seek their Ruby applications and u ...

  • Ext common problem of summing up

    scripts / ext / resources / css / ext-all.css / / EXT generic CSS, contains all the style (must) scripts / ext / resources / css / icon.css / / custom menu item or other storage page icon scripts / utils / HiTRUST-CMS.css / / old version of the payment sy

  • I heard good Ruby and Rails site

    1. Ruby Inside is said to be the best news station, the subscriber number 16xxx [img] http://www.rubyinside.com/simg/logo.gif "alt =" [/ img] http://www.rubyinside.com/ 2. Rails Inside is also a news station, the subscriber number of 3xxx [ ...

  • In the Linux platform to install and configure Ruby on Rails Detailed

    ruby on rails recommend the production environment is running Linux / FreeBSD / Unix, or Unix family of operating systems, using lighttpd + FCGI solution. The following will be my Linux operating system, lighttpd + FCGI, MySQL database as an example, comp

  • JS menu

    JS menu

  • JDBC example of a long time do not have JDBC forgot

    A back-up here to stay. The first: The second:

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