Basics of learning shell scripts [graphic]_linux shell

Source: Internet
Author: User
Tags echo command

A shell script is essential to day-to-day Linux system management, and if you don't write a shell script, you're not a qualified administrator. At present, many units in the recruitment of Linux system administrators, Shell script writing is a must test project. Some units even use the ability to write a shell script to measure the rich experience of the Linux system administrator. The author said that the purpose of this is only one, that is, let you take the shell script seriously, from the beginning to grasp the basic knowledge firmly, and then continue to practice, as long as your shell script written well, believe that your Linux job search road will be much easier. In this chapter, I will not introduce the shell script in much detail, but only take you into the world of shell script, if you are interested, please go to the Internet to download the relevant information or to the bookstore to buy related books.

Before you learn a shell script, you need to know a lot about the shell, which is the basis for writing a shell script, so I hope you can master it skillfully.

" What is Shell "

A simple understanding is the intermediate media that is used when the system interacts with the computer hardware, and it is just a tool for the system. In fact, there is a layer of stuff between the shell and the computer hardware that is the system kernel. For example, if the computer hardware is compared to a person's body, and the system core is the human brain, as for the shell, it seems more appropriate to compare it to human's facial features. Back to the computer, the user is not directly facing the computer hardware but shell, the user told the shell, and then the shell passed to the system kernel, then the kernel to dominate the computer hardware to perform a variety of operations.

The Linux release version (Redhat/centos) system installed by the author is called Bash, the Bourne Again Shell, an enhanced version of SH (Bourne shell). Bourn Shell is the first line of a shell, the founder of Steven Bourne, in order to commemorate his name is called Bourn Shell, seized sh. So what's the feature of this bash?

1 record Command history

We have knocked the command, Linux will be recorded, preset can record 1000 history commands. These commands are saved in the. bash_history file in the user's home directory. One thing you should know is that commands that run in the current shell are saved to the. bash_history file only if the user normally exits the current shell.

There's an interesting character about command history, and that's "!" Out. Commonly used have so several applications: (1)!! (Two consecutive "!" , indicating the execution of the previous instruction; (2)!n (where n is a number) represents the execution of the nth instruction in the history of command, for example, "!100" represents the 100th command in the execution of command history; (3)! string (string greater than or equal to 1), for example,!ta Represents the most recent instruction that starts with TA in the execution command history.

2) instruction and filename completion

At the beginning of this tutorial I introduced this function, remember? The right is to press the TAB key, it can help you complete a command, you can also help you complete a path or a filename. Press the TAB key two times consecutively, and the system will list all the instructions or file names.

3) Alias

There is also an introduction to Alias, which is one of the features that bash has in particular. We can use the alias to put a commonly used and very long instruction alias a simple and easy to remember instructions. If you do not want to use, you can also use Unalias to remove the alias function. You can see the current system preset alias by knocking the alias directly:



See, the System preset alias commands are just a few, you can also customize the command alias you want. The alias syntax is simple, alias [command alias]=[' specific Command '].

4) wildcard characters

Under Bash, you can use * to match 0 or more characters, and to match one character.

5) input and output from directional

Input redirection is used to change the input of the command, and output redirection is used to change the output of the command. Output redirection is more common and is often used to enter the results of a command into a file instead of on the screen. The command to input redirection is, the command for the output redirection is, the error redirect 2>, and the Append redirection >>, which will be described in more detail later.

6) Pipe character

The pipe character "|" has been mentioned earlier, leaving the result of the previous command running to the following command.

7) Operation control.

When you run a process, you can pause it (press ctrl+z), and then use the FG command to restore it, using the BG command to run it to the background, or you can make it stop (press CTRL + C).

" variable "

In the previous chapters, I have introduced the environment variable path, which is a variable of the shell preset, and usually the shell preset variables are uppercase. Variable, the simple point is to use a simpler string instead of some special meaning settings and data. In terms of path, this path replaces the absolute path setting for all commonly used commands. Because we have the path variable, we no longer enter the global path when we run a command, just hit the command name. You can use the echo command to display the value of a variable.

Besides path, home, logname, what are the system preset environment variables?



Use the ENV command to list all system variables for system presets. However, the user who logged in is different. The values of these environment variables are also different. What is currently displayed is the environment variable for the account root. The following is a brief introduction to the common environment variables:

Path determines which directories the shell will go to find commands or programs

Home Current User main directory

Histsize Number of history records

LogName The current user's login name

Hostname refers to the name of the host

Shell Front user shell type

Lang language-related environment variables, multiple languages can modify this environment variable

Mail storage directory for current user

PWD current Directory

The env command displays variables that are only environment variables, and there are a lot of system preset variables, and you can use the SET command to display all the variables in the system preset.

Limited to space, the author in the above example does not have all the results of the display screenshots. A set can display not only the system preset variables, but also the user-defined variables. User-defined variables? Yes, users can also define variables themselves.

Although you can customize variables, but the variable can only be effective in the current shell, do not believe you login to a shell to try?

You can then open a shell by using the Bash command, at which point the previously set myname variable does not exist, exiting the current shell and returning to the original Shell,myname variable. What about the variable that you want to set? There are two kinds of situations:

1 to be able to use the variable when all users in the system are logged in

You need to add "export myname=aming" to the last line of the/etc/profile file and run "Source/etc/profile" to take effect. At this point you run the Bash command or direct su-test account.

2) Just want the current user to use the variable

You need to add "export myname=aming" to the last line of the. bashrc file in the user's home directory and then run "source. BASHRC" to take effect. When you log into the test account again, the myname variable does not work. The source command used above is to speak about the configuration refresh that is currently set, that is, it can take effect without logging off and logging in.

The author uses "Myname=aming" in the above example to set variable myname, so what are the rules for setting the custom variable in Linux?

A. The format of the variable is "a=b", where a is the variable name, B is the content of the variable, and no spaces are allowed on either side of the equal sign;

B. Variable names can only be made up of English, numerals, and underscores, and cannot begin with numbers;

C. When the variable content with special characters (such as spaces), you need to add single quotes;

In one case, you need to be aware that the variable has a single quotation mark in its contents, which requires double quotes.

D. You can use inverted quotes if you need to use other commands to run results in variable content;

E. Variable content can be added to the contents of other variables, need to add double quotes;

Here if you accidentally add double quotes to single quotes, you won't get the results you want.

With the above examples you may be able to see the difference between single and double quotes: When you use double quotes, you don't cancel out the special characters that appear in them ($ here), and the special characters in single quotes all lose their function.

In the previous example, the author used the bash command several times, and if you run the bash instruction in the current shell, it will go into a new shell, which is the shell of the original shells, and you may want to check it with the Pstree command.

Pstree This instruction prints all the processes in the Linux system through the tree structure. Limited to the length of the author is not listed, you can directly enter Pstree view. After a variable is set in the parent shell, the variable is not in effect after entering the child shell, and if you want the variable to take effect in the child shell, use the export directive, which I used before.

Export is actually a statement of the meaning of this variable, so that the shell's child shell also know that the value of the variable ABC is 123. If export does not add any variable names, it declares all variables.

At the end, we are declared with our custom variables.

How do I set a variable in front of the light, and what if I want to cancel a variable? Just type "unset variable name".

With unset ABC, echo $ABC no longer outputs any content.

" configuration files for system environment variables and personal environment variables "

It says a lot of system variables, so where are the variables stored in Linux, and why do users automatically have these variables when they log in to the shell?

/etc/profile : This file presets several important variables, such as path, USER, LOGNAME, MAIL, INPUTRC, HOSTNAME, Histsize, UMAs, and so on.

/ETC/BASHRC : This file is mainly preset umask and PS1. This PS1 is when we are knocking on the command, the previous string of characters, such as the author of the Linux system PS1 is [root@localhost ~]#, you may wish to look at the PS1 value.

\u is the user, \h host name, \w is the current directory, \$ is that ' # ', if it is a normal user is shown as ' $ '

In addition to the two system-level profiles, there are several hidden files in each user's home directory:

. Bash_profile : Defines the user's personal path and the file name of the environment variable. Each user can use this file to enter shell information that is specific to their own use, and that file is executed only once when the user logs on.

. BASHRC : This file contains bash information dedicated to your shell, which is read when you log in and each time you open a new shell. For example, you can write user-defined alias or custom variables to this file.

. Bash_history : Records command history.

. Bash_logout : When you exit the shell, the file is executed. You can put some cleanup work into this file.

" special symbols in the Linux shell "

During your study of Linux, you may have contacted a particular symbol, such as "*", which is a wildcard symbol that represents 0 or more characters or numbers. The following author said a common use of special characters.

1. * : Represents 0 or more characters or numbers.

Test can be followed by no characters, can have more than one character, in short, or not all can match.

2.? : represents only one arbitrary character

Whether it is a number or a letter, as long as the one can be matched.

3. # : This symbol in Linux to indicate the meaning of the annotation, that is, "#" after the content of Linux ignored.

Linux is ignored by inserting "#" at the beginning or middle of the command. This symbol is used in a lot of shell scripts.

4. \ : de-ideographic character, the following special symbol (such as "*") revert to ordinary characters.

5. | : The pipe character, as it has been said many times before, is to throw the result of the command before the symbol to the command behind the symbol. The following commands mentioned here, not all commands are available, generally for document operation commands are more commonly used, such as cat, less, head, tail, grep, cut, sort, WC, uniq, tee, tr, split, SED, awk, etc., where g Rep, sed, awk is the tool that must be mastered for regular expressions and is described in detail in subsequent content.

6. $: In addition to the identifier used in front of the variable, there is also a magical use, that is, and '! ' Combined to use.

'!$ ' represents the last variable in the previous hit (perhaps the variable is not appropriate, in short, the last thing that appears in the previous command) For example, the top command is Test.txt, then entering!$ under the current command represents Test.txt.

1 ) grep : Filters One or more characters, which will be described in detail in subsequent content.

2 Cut: intercept a field

Syntax: cut-d "separator character" [-CF] n Here's n is the number

-D: followed by the separator character, the separator character should be enclosed in double quotes

-C: followed by the first few characters

-F: The following is the first block

-D followed by the separator character, where the colon is used as the split character, and-F 1 is to intercept the first paragraph, the space between-F and 1 is optional.

-C after can be 1 digits N, can also be an interval n1-n2, can also be multiple numbers n1,n2,n3

3) sort: used as a sort

Syntax: sort [-t separator] [-KN1,N2] [-NRU] Here's N1 < N2

-T separator: effect with cut's-D one meaning

-N: Sorting with pure numbers

-R: Reverse Sort

-U: To repeat

-KN1,N2: Sorted by N1 interval to N2 range, can write only-kn1, that is, sort N1 fields

4 WC : Count the number of lines, characters, and words in the document, the commonly used options are:

-L: Statistics of rows

-M: Statistics of characters

-W: Statistics number of words

5 ) uniq : To repeat the line, the author commonly used only one option:

-C: Counts the number of duplicate rows and writes the number of rows to the front

One thing to note is that before uniq, you need to sort before you can uniq, otherwise you will not get what you want, the author of the experiment above is already sorted so omit the step.

6 ) Tee : followed by a filename, similar to redirect ">", but the specific weight is directed to one more feature that is displayed on the screen while the file is written to the file that follows.

7 ) TR : Replaces characters that are commonly used to handle special symbols appearing in documents, such as ^m symbols that appear in DOS documents. There are two commonly used options:

-D: Delete a character,-D followed by the character to be deleted

-S: Remove repeated characters

The most common is to turn lowercase to uppercase: TR ' [A-z] ' [A-z] '

Of course, replacing a character is perfectly OK.

However, substitution, deletion and repetition are all directed at one character, with certain limitations. If it is no longer useful for a string, the author suggests that you simply understand this TR and you will learn more about the tools you can implement for string manipulation.

8 ) Split : Cutting documents, common options:

-B: Split the document by size, in bytes

Format as above example, the following passwd is the prefix of the file name after the partition, the file name is Passwdaa, Passwdab, Passwdac ...

-L: Split document by number of rows

6. ; : Semicolon. Usually we are in a line to knock a command, and then enter the run, then want to run in a row of two or more than two commands how? You need to add a ";" between the commands. Out.

7. ~ : User's home directory, if it is root is/root, ordinary users are/home/username

8. & : If you want to put a command in the background, you need to add this symbol. Typically used for a very long time to run a command.

Use jobs to view the tasks that are performed in the background in the current shell. FG can be transferred to the front desk for execution. The Sleep command here is the meaning of hibernation, followed by numbers, in seconds, in a shell script that is often used as a loop.

At this point you click CTRL +z to suspend it, and then enter BG to run back into the background again.

In the case of multitasking, if you want to transfer the task to the foreground, the FG is followed by the task number and the task number can be obtained by using the jobs command.

9. , >>, 2>, 2>> : In front of the overweight directional symbols > and >> respectively represent the meaning of substitution and append, and then there are two symbols here 2> and 2>> Indicates error redirection and error append redirection, when we run a command to complain, the error message is output to the current screen, and if you want to redirect to a text, use 2> or 2>>.

[] : brackets, in the middle of a character combination, representing any one of the middle characters

&& and | |

The semicolon is mentioned above and is used for delimiters between multiple commands. There are also two special symbols that can be used in the middle of more than one command, namely "&&" and "| |". The following is a full list of these situations:

1) Command1; Command2

2) Command1 && Command2

3) Command1 | | Command2

Use ";" , the Command2 is executed regardless of whether the Command1 is executed successfully, and when the && is used, the Command2 executes only after Command1 is executed, otherwise the Command2 does not execute; , Command1 execution succeeds after Command2 does not execute, otherwise to execute Command2, in short Command1 and Command2 always have a command to execute.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.