1. What is shell?
In fact, I have heard of shell before I came into contact with Linux. At that time, I was talking about shell programming and I knew nothing about it. But surprisingly, I remember this term when my memory is really bad. Okay, let's talk nonsense. In the previous article(1) Linux?
Ubuntu or centos? Linux Installation. Computer users communicate with the kernel through the interface (shell, Kde, etc.) to control computer hardware to execute the functions we want to implement. Shell literally refers to the shell, that is, the shell wrapped outside the core (kernel. It is one of the tools that our users use to communicate with the core.
2. Why should I learn shell?
Now Linux is quite user-friendly. For example, the Ubuntu window interface can already be used by most users. So why should we learn shell? A: Although the X-window-based operation interfaces are quite complete and have powerful functions, they are all just a group of applications that integrate the useful software, not a complete suite. Therefore, when you upgrade the management modules of other suites, the configuration will be very troublesome. Even the X-Window Interfaces set by different release versions are different, and learning is also difficult. In addition, the text interface transmission speed is relatively fast during remote connection.The most important thing is that it gives you a better understanding of Linux. As a general user, only learning the operation interface can solve the vast majority of problems. But as a system manager or developer, learning shell is necessary.
3. bash shell?
After knowing what shell is, let's get a general idea of the shell version. The specifics will not be discussed in detail. The common shells in UNIX generally include the Bourne shell (SH), the C shell preset in Sun, the commonly used K shell and tcsh. The shell used in Linux is the Bourne again shell (BASH), an enhanced version of the Bourne shell, developed based on the GNU architecture. What shell can be used in Linux? How many shells can be used in Linux (taking centos 6.x as an example? Check/etc/shells.
This file contains the following types of shells that can be used:
/Bin/sh (replaced by/bin/bash)
/Bin/bash (the default shell in Linux)
/Bin/tcsh (integrating C shell to provide more functions)
/Bin/CSH (replaced by/bin/tcsh)
Since there are so many shell types, which one should we learn? In Linux, the default shell is bash shell, so we can learn it first.
4. BASH Shell functions
Bash is compatible with SH. Main functions:
1) command memory function. Bash can remember the commands used. You only need to press the up or down key on the command line to find a command entered before/after. In most released versions, the default command memory function can memorize up to 1000 commands. That is, almost all commands you have issued have been recorded.
These commands are recorded in the. bash_history file in your home directory (/home/username directory. However ,~ /. Bash_history (~ Refers to the Home Directory, that is, the/home/user name directory .) Logs the commands that were run during the last logon. The commands entered during this logon are stored in the cache and will be recorded only after the system is logged out ~ /. Bash_history file.
2) command and file complementing functions ([Tab] Key Usage)
The command and file completion functions allow you to: Make sure that the input data is correct. The rules for using the tab key are as follows:
[Tab] after the first word of a command string, the command is supplemented;
[Tab] after the second word of a string of commands, the file is complete.
Command completion: if you do not want to press too many buttons during command execution, for example, the command pcprofiledump. If you enter pcprofile, press the [Tab] key, then Bash will automatically connect the dump next to it! What if there are repeated commands? Press [Tab] twice to list all duplicate commands!
File Name completion: If you use VI to read a file, such as/etc/man. config, when you enter VI/etc/man. then press the <tab> key to automatically complete the file name!
3) command alias configuration (alias)
If I need to know all the files under this directory (including hidden files) and all the file attributes, I need to use the LS-Al command, which is a little troublesome. Is there a faster way? You can use the command alias. Use alias to name the LS-Al command LM. Enter LM in Bash to replace the LS-Al command. The specific practices are as follows:
Alias LM = 'LS-al'
4) Job control and foreground background control
This part will be discussed in detail in subsequent resource management sections. Before use, background control can make the work more smooth. Jobs can cause us to throw work to the background at any time, and we are not afraid to accidentally use Ctrl + C to stop the program. You can also perform multiple tasks in a single user environment.
5) shell scripts
I don't know if you have heard of batch processing files, that is, writing a bunch of commands to a file. In Linux, the shell scripts function is more powerful. It can write continuous commands that need to be issued in daily life into a file, which can be used for host detection in interactive mode, it can also be designed based on the environment variables and related commands provided by shell, which is equivalent to the functions of the programming language.
Wildcard (wildcard)
In addition to the complete string, bash also supports many wildcards to help you execute commands. For example, how many files starting with X in the/usr/bin directory? Run the LS-L/usr/bin/x * command. In addition, there are other available wildcard characters to help accelerate user operations.
5. How to issue commands in bash shell?
Command [-options] parameter1 parameter2... That is, the command [-Option] parameter 1 parameter 2...
The command is the name of the command, such as changing the command cd in the directory; [] does not actually appear,-appears, followed by the Command Option. For example, the LS-Al parameter is the command parameter. (Note: If the command is too long, you can use \ to continue the command to the next line)
6. Setting variables and variables
1) variable?
How does the system know where the LS command is stored when the LS command is entered? This is because there is a path variable, and the system will find this command in sequence through the path set in this variable. If not found, the command not found will be output. If found, the command will be executed. When writing a script, if there is a path in it and it is used in many places, it will be very troublesome to modify it one by one when there is a need for modification. If there is a variable, you only need to modify the variable value. In other places, you do not need to modify the variable because the referenced variable is used. Therefore, a variable is a set of characters or symbols used to replace some settings or a string of reserved data.
2) echo
I just introduced the concept of variable. How can I display the variable content? Use the echo command. The usage is Echo $ variable. For example, Echo $ path
3) ENV
The echo command is used to display the variable content. How do we know the preset variable content in the system? Use the Env command.
Env is short for environment. This command reads the main variables in the current system! But can we still customize variables? Therefore, apart from the Env command to read environment variables, there is also an instruction that can read all the variable data in the current system, called set! In addition to reading the above data, set also reads the additional information (usually related to user settings !)
4) Set
Note: because there are too many variables in the system, the above picture is only part of the output results of the Env command and set command.
5) custom Variables
How do I customize variables? To make the variable valid for all users, You need to modify the/etc/profile file. If you only want to be valid for the current user, switch to the current user's home directory and then modify it. bashrc or. bash_profile file. Name the variable and assign values to the variable.
6) variable naming rules
As for naming variables, the naming rules for variables are as follows:
- The variable and the variable content are connected with the equal sign "=;
- Equal signs cannot be directly followed by space characters;
- The variable name can only contain English letters and numbers, but cannot start with a number;
- If there is a space character, you can use double quotation marks "or single quotation marks" '"to combine the variable content, but pay special attention to the fact that special characters in double quotation marks can retain the variable property, however, special characters in single quotes are only common characters;
- If necessary, the special characters (such as enter, $, \, space character, and ') must be converted into general characters by the Escape Character;
- You can use the quote "'command'" for the information provided by other commands in a string of commands '』;
- If the variable is an expanded variable, double quotation marks ("$ path":/Home ") and $ variable names must be used to accumulate the content;
- If the variable needs to be executed in another subroutine, you need to use export to make the variable executable, for example, "Export path 』;
- Generally, upper-case characters are system preset variables. You can use lower-case characters to set variables (purely based on user interests and hobbies );
- The method for canceling a variable is "Unset variable name 』.
7) General variable settings
1 name = Shan <= error because the variable cannot start with a number
Name = Shan <= error because the equal sign cannot be directly followed by Spaces
Name = Shan <= Correct
Name = Shan name <= Error. When the variable contains spaces, double quotation marks must be added.
Name = "Shan name" <= Correct
Name = "Shan's name" <= Correct
8) variable accumulation settings
Name = $ nameaa <= error. You must add double quotation marks to the original variable.
Name = "$ name" AA <= correct. The echo $ name command displays Shan's nameaa.
Name = "$ name": AA <= Correct
Name = "$ name: AA" <= Correct
9) Extend the variable to the subroutine
Name = "Shan's name" <= set the name variable
Echo $ name <= display name variable content
Shan's name
/Bin/bash <= open a bash subroutine
Echo $ name <= display name variable content
<= An empty string is displayed because name cannot be used in a subroutine.
Exit <= exit the bash shell of the subroutine
Export Name <= This extends the name variable to the subroutine.
10) commands in the command
CD/lib/modules/'uname-R'/kernel
The preceding command restricts the nested command 'uname-R' and then attaches the result to the entire command.
11) Cancel variable settings:
Unset name
12) What is the difference between single quotation marks and double quotation marks in variable settings?
A: The biggest difference between single quotes and double quotes is that double quotes can still retain the content of variables, but single quotes can only be general characters without special symbols. Let's explain in the following example: If you have defined a variable named name = Shan, and want to define the content of "Shan is me" in myname, how can we define it?
[Root @ test root] # name = Shan
[Root @ test root] # echo $ name
Vbird
[Root @ test root] # myname = "$ name is me"
[Root @ test root] # echo $ myname
Shan is me
[Root @ test root] # myname = '$ name is me'
[Root @ test root] # echo $ myname
$ Name is me
13) when single quotes are used, $ name will lose the original variable content, only the display type of general characters! Be especially careful here!
For example, what is the meaning of the quote (') (Note: Non-') symbol in the instruction issuing process?
A: In a string of commands, the commands within 'will be executed first, and the execution results will be used as external input information! For example, uname-R will display the current core version, and our core version is in/lib/modules. Therefore, you can first execute uname-R to find the core version, then run "CD directory" to the directory. Of course, you can also execute
CD/lib/modules/'uname-R' is directly stored in this directory.
14) Valid range of variables:
"Variable settings only exist in the current shell environment. They will not exist in the next or subprogram !』 To allow the variable to be used in the next program, use the Export command! In addition to the shell parent and subprogram, in the script writing process, because some software will use more than two scripts as a complete suite! That is to say, if you have two programs, one is scripts1.sh and scripts2.sh, and scripts2.sh will reference the variable scripts1.sh, in scripts1.sh
Please set the variables in "10 million records can be export Settings", otherwise your variables will not be referenced between two scripts! After the scripts execution is complete, the variable set in the scripts just now becomes "invalid 』.
15) read, array, Eval
The read command can be used to dynamically set the command content, instead of static settings.
Read variable name. After you press enter, you will wait for the user to enter the variable content. For example, enter read name [Press enter], then enter Shan, and then use echo $ name. The output result is Shan.
Array is used to create an array of variables, while eval can use the variables of variables. For example
Day = 2
Year = Day
Echo \ $ year <= \ is an escape character, that is, the first $ after "\" is changed to a general character.
$ Day
Eval echo \ $ year <= after Eval is added, the variable \ $ year is changed to a variable (that is, $ day)
2
16) History ,! Number and! Command
Use the history command to view commands entered in the past. The output content is the number command name. For example, 66 LS-Al. Now, I can use it! 66 to execute the LS-Al command, you can also use! Ls to execute the LS-Al command. Number is the sequence number of the command, and command is the first few letters of the command. If you enter !!, Indicates executing the previous command (the command just entered)
7. bash shell setting file
1) system setting value: the setting file that is read first after each user enters the bash shell. There are mainly the following:
/Etc/profile: set several important variables, such as path, user, mail, hostname, histsize, and umask. In addition, there are the/etc/bashrc and/etc/man. config files. The specific content can be Baidu or Google.
2) Personal setting value: It is only for the current user's own files. That is, several hidden files in the personal home directory. Mainly include:
~ /. Bash_profile: defines the personal path and environment variables. You can modify your personal path here, or in ~ /. Modify it in the personal variable bashrc.
~ /. Bash_history: The purpose of this archive is to record the commands you have used, and when you search for them again or directly using history, you can find the commands you have used.
~ /. Bash_logout: defines what Bash will do for you when you log out the shell! Usually, only clear the screen is required by default.
8. Source
If I need to read the content of the current configuration file once and re-logout and then login, is there a way to directly read the variable configuration file without logging out? Of course. Use source! Specific format: Source variable setting file
9. All-round characters and special characters
Symbol content * Ten-thousands of characters, representing one or more characters (or numbers )? A character represents a letter # annotation. This is most often used in scripts and is considered as a description! \ Escape character, "special character or universal character" is restored to a general character | the definition of the two pipeline commands is separated; the definition of continuity commands (note! Different from pipeline commands )~ The user's home directory $ is the variable to be added before the variable to replace the value & turn the command into a background! The meaning of "Non" not in the logic operation sense! /Path-separated symbols>,> output-oriented, which are single quotation marks "Replace" and "accumulate", without the function of variable replacement "with the function of variable replacement! The middle of ''two ''is the command that can be executed first! () In the middle is the combination of the sub-shell's start and end [] in the middle is the character {} in the middle is the combination of the command block! Press Ctrl + C to terminate the current command Ctrl + D and enter the end (EOF). For example, when the mail is over, CTRL + m is the Enter! CTRL + s pause screen output Ctrl + q resume screen output Ctrl + U under the prompt character, delete the entire command Ctrl + z pause current command
10. How to issue continuous commands:
The two commands are successively written together and can be written in the following three ways:
Command1; command2. It indicates that command2 will be executed no matter what the command1 execution result is!
Command1 & command2. It indicates that if command1 has no error, command2 will execute
Command1 | command2. Indicates that if command1 has an error, command2 will execute
11. absolute and relative paths
The path starting with "/" is an absolute path, and the path not starting with "/" is a relative path. In addition, '.' indicates the local directory, '..' indicates the upper directory ,'~ 'Indicates the home directory.
Note: Adding '.' before the file name indicates that the file is a hidden file.
12. Command redirection
Command redirection: stores your current data in a specified place! The most commonly used method is to convert the current screen output data to a file, which can be written as follows: ls-L/> test, symbol> directs the output result to the file test.
If you only execute LS-L/, the files and directories in the root directory will be listed on the screen; but when you use> to direct to the file test, the screen will not display any information, but will output the result you just executed to the file test.
Note: If the file (that is, test) does not exist during redirection, the system automatically creates the file. If the file exists, the system first clears the file content, then write the data!
In addition to this> symbol, there are three output conditions in the bash Command Execution Process:
Standard input; Code: 0; or stdin; usage: <
Standard output: the code is 1; or stdout; the method used is 1>
Error output: the code is 2; or stderr; the method used is 2>
The basic instruction writing method is:
Command |
1> 1> 2> 2> < |
Device or file |
Here we will illustrate several common symbols and devices in the Command redirection:
<: Read the parameter file from the right of <;
>: Output the correct data originally output by the screen to> file (File Name) or device (device, such as printer) On the right;
>>: Output the correct data originally output from the screen to> on the right. Different from>, the file will not be overwritten, the new data will be added to the end of the file in the "add mode;
2>: Output Error Data from the screen to the right of 2>.
/Dev/null: it can be said to be a black hole device!
For example:
Ls-Al 1> list.txt 2> error.txt
The output from the displayed data to list.txt, and the error output to error.txt
Ls-Al 1> list.txt 2> & 1
Output the displayed data to list.txt without argument or error
Note: ls-Al 1> list.txt 2> list.txt is incorrect.
13. Pipeline command (PIPE)
The output data will appear during bash command execution! So how should we set this group of data to get the desired format after several procedures? This involves the issue of visiting the command (PIPE). The pipeline command uses the definition symbol "|! In addition, pipeline commands are different from "issuing commands continuously", which we will explain below. Let's take an example to illustrate a simple pipeline command.
Suppose we want to read the "Number of times" of the root login from the last command. What should we do? We only need "times 』. The steps are as follows:
Execute last to retrieve all the login data for this month;
Use grep to extract the root of the above output data (stdout;
You can use the WC command to calculate the number of rows!
Because the last output is a line that represents one login, as long as a few lines are calculated, it means several logins! In the preceding three steps, we can gradually filter the last data to obtain our data! The entire command can be written as follows:
Last
Last | grep Root
Last | grep root | WC-l
You can execute "last" and then gradually add it to "Last | grep root". Then, you can know exactly why this is done! The pipeline command "|" can only process the correct information sent through the previous command, that is, standard output (stdout) information. It has no direct processing capability for stdandard error, remember. The overall pipeline command can be expressed as follows:
The section in each pipeline is "command! The input of the next command is from the output of the previous command!
Next, let's talk about some basic pipeline command instructions:
1) Cut
The command format is cut [-DCF] fields.
Parameter description:
-D: followed by characters to be separated. The default character is a space character.
-C: followed by the nth character
-F: The blocks to be followed
2) sort
The command format is sort [-T separator] [(+ start) (-end)] [-NRU].
Parameter description:
-T separator: Use a separator to separate different intervals. The default Delimiter is tab.
+ Start-end: sorts data from the start interval to the end interval.
-N: sorts data by numbers only. Otherwise, the data is sorted by text.
-R: reverse ang sorting
-U: the same row that appears, only listed once
3) WC
The command format is WC [-LMW].
Parameter description:
-L: number of rows
-M: The number of characters.
-W: How many words
4) uniq
Only one
5) tee
In command redirection, if data is output to a file, no data is displayed on the screen. If you need to display data on the screen, add tee.
6) tr
Many regular expressions are used. Regular Expressions will be described later. Tr [-Ds] set1
Parameter description:
-D: Delete the set1 string.
-S: replace repeated characters
7) Split
Used to split files. Specific format: Split [-BL] leading character of the input file output file
Parameter description:
-B: file size.
-L: minute by number of rows
Some words written at the end:
The complete bash shell should include shell script. Write this part first. Writing a blog takes more time than reading a book, but writing it is a summary. So it's better to write it ~
Reprinted please indicate the source: http://blog.csdn.net/iAm333