Linux operating system shell

Source: Internet
Author: User

1 Linux operating system Shell1.1 shell script

When a command is not executed on the command line, but is executed from a file, the file is called a Shell script.

Attention:

Shell scripts typically use. sh as the suffix, but are not required.

The Shell script is in the behavioral unit and is executed in a single line when the script is executed.

Shell scripts are plain text files

, the Shell is a powerful, interpretive programming language

1.2 Shell Script Component 1.2.1 Shell variable

Variable name does not add dollar sign ($) when defining a variable

There can be no spaces between the variable name and the equals sign, which is different from other programming languages, and the rules that name the variable name follow:

<1> the first character must be a letter (a-z,a-z)

<2> the middle cannot have spaces, you can use the underscore (_)

<3> cannot use punctuation

<4> cannot use keywords inside bash (ex: CP)

1.2.2 Input/Output

1. Input

Assigning values to variables

Example: name=1

Read from standard input

Read

Example: Echo–e "What ' s your name: \c"

Read name

echo "My name is $name"

2. Output

Echo (Common)

1.2.3 Read

READ: Receive input from standard input (keyboard)

For example:

#!/bin/bash                // give the following command to bash under/bin execution #The use of the Read method  //  Comment on the use of Read echo"Enter your name:"   //-N: No line break display Read name                 // input from keyboard Echo " Hello $name, Welcome to my family " // Display Information

The above command can be condensed with-p (abbreviated)

" Enter your name: " name   //  -P: Display the message, read the variable only nameecho"Hello $name, Welcome to My family"

1.2.4 Wildcard characters

A wildcard is a system Level , wildcard characters are used on filenames, such as finding Find , ls , CP , and so on

In everyday Linux Use, there are many times when you may need to perform a single operation (such as RM) on multiple file system objects at once. In these cases, it is often annoying to enter many files on the command line:
$ rm file1 file2 file3 file4 file5 file6 file7file8
To solve this problem, you can take advantage of the Linux built-in wildcard character support. This support is also called "globbing" (for historical reasons), allowing you to specify multiple files at once by using the wildcard pattern. Bash and other Linux commands interpret this pattern by looking up on disk and finding any files that match it. Therefore, if you have files from File1 to File8 in the current working directory, you can delete these files by entering the following command:

RM file [1-8]

Or, if you only want to delete all files with file names that begin with filename, you can enter:

RM File*

Alternatively, if you want to list all file system objects that start with g in/etc, you can enter:

ls -d/etc/g*

Now, what if you specify a pattern that does not have any file system objects matching it? In the following example, we try to list all the files in/usr/bin that begin with ASDF and end with JKL:

ls -d/usr/bin/asdf*jkl

Here is a description of what happened. Typically, when we specify a pattern, the pattern matches one or more files on the underlying system, and bash replaces the pattern with a space-delimited list of all matching objects. However, when a pattern cannot find a matching object, bash ignores parameters, wildcards, and so on, leaving it as is. Therefore, when "LS" Cannot find the file/usr/bin/asdf*jkl, it will error. The valid rule here is that the Glob mode can be extended only if it matches objects in the file system.

Wildcard Syntax: *
* will match 0 or more characters . That means "everything can be". Example:
*/etc/g* matches all files that start with g in/etc.
*/tmp/my*1 and/tmp start with my, and all files ending with 1 are matched.

Wildcard Syntax: ?
? matches any single character . Example:
* myfile? Matches any file with a file name of MyFile followed by a single character.
*/tmp/notes?txt will match/tmp/notes.txt and/tmp/notes_txt if they exist.

Wildcard Syntax: []
The wildcard character is associated with a. Similar, but allowed to be specified more precisely. To use the wildcard character, place all the characters you want to match within [] . The resulting expression will match any of the characters in []. You can also use-to specify a range, or even to combine ranges. Example:
* Myfile[12] will match myfile1 and Myfile2. The wildcard can be extended as long as there is at least one such file present in the current directory.
* [Cc]hange[ll]og will be matched with ChangeLog, ChangeLog, ChangeLog, and ChangeLog. As you can see, it is useful to use the parentheses wildcard when matching a variant in uppercase.
* ls/etc/[0-9]* will list all files in/etc that begin with a number.
* ls/tmp/[a-za-z]* will list all files in/tmp that begin with uppercase or lowercase letters.

Wildcard Syntax: [!]
In addition to not matching any characters in brackets, [!] Construction is similar to the [] construct, as long as it is not a character listed between [! and] , it will match any character. Example:
* RM Myfile[!9] will remove all files named MyFile plus one character except Myfile9.

1.3 Shell Script Coding specification

1, to #! Start: Notifies the system which interpreter to use to execute the script

#!/bin/bash (Common)

#! /bin/ksh

Note: Ksh is used more on UNIX; bash is used on Linux more

2. Comments

Lines that begin with # are comments, which are ignored by the annotation viewer.

1.4 The creation and execution of shell scripts

1. Creation of shell scripts

Editing a script file using a text editor

VI test.sh

Add executable permissions to a script file

chmod +x test.sh

2. Execution of shell scripts

Executing in a child shell

Bash test.sh

SH test.sh

For example:

Note: The default value of the PATH environment variable does not contain the current directory and should be used if the script file is in the current directory./script-file (./represents the current directory)

For example:./test.sh

1.5 Shell script debugging

1. Sh–x Pin Name

This option allows the user to track the execution of the script, at which point the shell processes each command in the script as follows: Performs the substitution first, then displays, then executes it.

When the shell displays a row in the script, a plus sign "+" is added at the beginning of the line

2. SH–V Pin Name

Print the lines in the script as you entered before executing the script

3. Sh–n Pin Name

The script is checked for syntax, but the script is not executed. If there is a syntax error, the shell will make an error, and if there are no errors, no content is displayed.

1.6 Shell Script Type

1. Interactive scripting

The script can read the user's input, feedback the information to the user in real time (output some information)

Such a script is more flexible, the parameters of each execution can be dynamically set by the user

User interface is more friendly, but not for automated tasks (such as cron tasks)

In simple terms: The interactive mode is the shell waiting for your input, and immediately executes the command you submitted

2. Non-interactive scripting

No need to read the user's input, and do not have to feed the user some information

Each execution is predictable because it does not read user input and the parameters are fixed

Can be executed in the background

Simply put: The shell does not interact with you, but instead reads the commands stored in the file and executes them. When it reads the end of the file, the shell terminates.

1.7 Flow control Statement 1.7.1 IF

The IF statement determines which branch to execute by using relational operators to determine whether an expression is true or false. The Shell has three types of statements:

If ... fi statement

If ... else ... fi statement;

If ... else ... elif. Fi statement.

1. If ... fi statement

Format:

If "Conditional expression"

Then

Statement block

Fi

If the conditional expression returns TRUE, then the statement block after then is executed, and if it returns FALSE, no statement is executed

2. If ... else ... fi statement

Format: "Conditional expression"
Then

Statement Block 1

Else

Statement Block 2

Fi

3. Elif ... fi statement

1.7.2 while

While expr//execute expr

Do// if expr's exit status is 0, enter the loop, or exit while

Commands//Cycle body

Done//Loop end flag, return to top of loop

1.7.3 for

For variable in value 1 value 2 ...

Do

Code

Done

1.8 Jobs
    1. Monitor memory after 20%, alarm and save to Mem.log file

#!/bin/Bash #This is monitor the usage of Mem#andifThe usage rate exceeds -%, please check it#get the total and usedtotal=` Free-M |sed-N'2p'|awk '{print $}'' used=` Free-M |sed-N'2p'|awk '{print $}'' #Get the Usageusage=`Echo "$Used * 100/$Total"|BC ' #whether rate is exceeds than -%if[$usage-ge - ] Then    Echo-N 'Date "+20%y-%m-%d%h:%m:%s"' >>/home/wuzhenru/Mem.logEcho-E"\twaring:the usage of MEM is $usage%, please check it.">>/home/wuzhenru/Mem.logElse    Echo-N 'Date "+20%y-%m-%d%h:%m:%s"' >>/home/wuzhenru/Mem.logEcho-E"\tthe usage of MEM is OK!">>/home/wuzhenru/Mem.logfi

The suspended mirror occupies the sum of memory, and when the sum is greater than 2%, the corresponding time and memory are written in the log.

Execution Result:

Jll.log

Linux operating system shell

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.