Chapter 1 of Linuxshell script strategy

Source: Internet
Author: User

1.1 Introduction

1. After the terminal is opened, a prompt will appear, in the following format:

Username @ hostname $ or root @ hostname #

2 $ indicates a common user, and # indicates a Super User. Super Users have the highest permissions in Linux.

3 There are two ways to run scripts

Sh script. sh or path script (path is the directory where the script is located)

4. In bash, each command is separated by a semicolon ";".

1.2 terminal Printing

1 echo is the basic command used for terminal printing. By default, echo adds a line break after each call.

2 another command that can be used for terminal printing is printf. The parameters of printf are the same as those of the printf function in C language.

3 by default, echo will append a line break to the end of the output text. You can use-n to ignore the ending line break.

4. If an escape sequence is required, echo-e is used to "include the character string of the escape sequence ".

 

1.3 game variables and Environment Variables

1. We can use pgrep to quickly find the pid of a process. If a gedti is running, we can quickly know the id of the gedit process through pgrep gedit.

2. You can assign values to a variable using the following methods: var = value, var is the variable name, and value is the variable value. If value does not contain any blank characters, then he does not need to use quotation marks for reference. Otherwise, he needs to use quotation marks for reference.

3. Environment is a variable inherited from the parent process, which is not defined in the current process.

4. the export command is used to set environment variables.

5. Obtain the length of the string =$ {# var}, which can be used to evaluate the length of the variable var.

 

1.4 perform mathematical operations through shell

1 In the bash environment, let () and [] can be used for basic arithmetic operations. In advanced operations, expr and bc can be used.

2 when using let, you do not need to add $ before the variable name. For example, let res = num1 + num2

3. let supports ++, --, and other operations.

4. The usage of the [] operator is similar to that of the let command, for example, res = $[num1 + num2].

5 you can also use (), but when () is used, add $ before the variable name, for example, res = $(num1 + num2 ))

6. We can use scale = 2 to set the number of decimal places to 2.

1.5 playback file descriptors and redirection

1. The file descriptor is an integer associated with the file input and output. They are used to trace and open files. The most common file descriptors are stdin, stdout, and stderr.

2. The file descriptor is an integer associated with an open file or data stream. The file descriptors 0, 1 and 2 are reserved by the system.

0-stdin standard input, 1-stdout standard output, 2-stderr standard error

3. Use the following method to redirect the output text to a file.

Echo "this..."> out, You can redirect the output string to the out file.

4> and> are different. The former clears the file before writing the content, while the latter adds the content to the end of the existing file.

5. When the redirection operator is used, the redirected content will not appear on the terminal, but will be directly imported into the file. The redirection operation uses standard output by default.

6> equivalent to 1>; For >>, equivalent to 1>

7. With redirection, we can use stdin to read data from the file. cmd <file

8. You can use the exec command to create a custom file descriptor.

1.6 arrays and associated Arrays

1 bash supports arrays and associated arrays at the same time. Normal Arrays can only use integers as array indexes, while associated Arrays can use strings as array indexes.

2 There are many ways to define arrays

First: array_var = (1 2 3 4 5). These values are stored in the continuous position where the index starts with 0.

Type 2: array_var [0] = 1

Array_var [1] = 2

......................

3 print the array content of a specific element, $ {array_var [index]}. The content indexed as index is printed.

4. Print all values in the array as a list, $ {array_var [*]}

5 print the length of the array $ {# array_var [*]}

6. In an associated array, we can use any text as an array index. In an ordinary array, we can only use an integer as an index.

7 first, we need to declare A variable as an associated array named declare-A ass_array.

1.7 use aliases

1. aliases can be implemented in multiple ways. functions or alias commands can be used.

2. Create an alias new_command = 'command' as follows'

3 The Role Of The alias command is temporary. We need to write it in ~ /. Bashrc, and then use source ~ /. Bashrc so that you can use aliases for a long time

4. If you want to delete an alias, you can use unalias or directly delete it ~ /. Bashrc

1.8 obtain terminal information

1. Obtain the number of rows and columns of the terminal. tput cols and tput lines

2 print the current terminal name tput longname

3. Delete all content from the current cursor position to the end of the line. tput ed

1.9 get/set date and latency

1. We use date to print the date

2. Print the date + % s of Ji yuan, which is defined as the total number of seconds from 00:00:00, January 1, January 1, 1970 to the current time.

3. Use the format string combined with + as the parameter of the date command. You can print the corresponding format and date according to your selection.

4. We can use sleep time to delay time and seconds.

5 tput SC is used to store the cursor position, tput rc is used to restore the cursor position, and tput ed is used to clear the content from the current cursor position to the end of the row.

1.10

1. Use-x to start the shell script for tracking and debugging. Run the script with the-x flag to execute each line of commands and the current status.

2. In each case, we can enable or disable debugging printing in the script.

Set-x displays parameters and commands during execution

Set + x disable debugging

Set-v: The input is displayed when the command is read.

Set + v disable input Printing

3. We can directly use shebang #! /Bin/bash #! /Bin/bash-xv debugging without other explicit items

1.11

1. Function Definition

Function fname (){

Statements

}

Or

Fname (){

Statements

}

2. If the function name is used, a function fname can be called and the fname function is executed.

3 parameters can be passed to function fname arg1 arg2

4. Similarly, parameters can be passed to scripts and accessed through scripts.

$1 is the first parameter.

$2 is the second parameter.

$ N is the nth parameter.

$ @ Is extended to "$1" "$2" "$3"

$ * Expanded to "$ 1c $ 2c $3", where c is the first character of IFS

$ @ Is often used. Because $ * treats all parameters as a single string, it is rarely used.

5. A value is returned after each command in bash is executed. If the value is 0, the execution is successful. Otherwise, the execution fails.

1.12

1. We use pipeline pipe to connect to every filter, for example, $ cmd1 | cmd2 | cmd3. Here we combine three commands. The cmd1 output is passed to cmd2, while cmd2 is passed to cmd3, the final output will be printed or imported into a file.

2. We have two methods to get the output of the command sequence.

First: output = $ (cmd). In this way, the result of the cmd command is output to the output.

Type 2: output = 'cmd'. The result of the cmd command is output to the output.

3. if we use the shll or anti-reference method to read the command output into a variable, we can put it in double quotation marks to retain spaces and line breaks.

1.13 field delimiter and iterator

1. The inner field delimiter IFS is an important concept in shell scripts. The default IFS is a blank character (line break, tab or space)

2. We can easily generate different sequences.

Echo {1 .. 50} can generate a sequence from 1 to 50.

Echo {a. z} can generate a sequence from a to z.

3. for Loop

For I in list

Do

Statements

Done

4 while LOOP

While condition

Do

Statements

Done

 

1.14 comparison and Testing

1 if condition

If condition

Then

Statements

Elif condition

Statements

Else

Statements

Fi

2. We can use logical operators to reduce the use of if else.

[Condition] & action if the condition is true, execute action

[Condition] | action if the condition is false, the action is executed.

3 arithmetic comparison

-Eq: equal

-Ne: not equal

-Gt: greater

-Lt: less

-Ge: greater than or equal

-Le: less than or equal

4 File System Tests

[-F $ file] returns true if the specified file is a normal file.

[-X $ file] returns the true result if the given object has the execution permission.

[-D $ file] returns true if the given file is a directory.

[-E $ file] returns true if the file exists.

[-C $ file] returns true if the specified file is a character device file.

[-B $ file] returns true if the given file is a block device file.

[-W $ file] returns true if the given file has some Permissions

[-R $ file] returns true if the file has the read permission.

[-L $ file] If the given file is a symbolic link file, the system returns true.

5 string comparison

1 When comparing strings, it is best to use double brackets, because sometimes an error occurs when using single brackets.

2 [[$ str1 = $ str2], returns true if str1 is equal to str2

[[$ Str1! = $ Str2], returns true if str1 is not equal to str2

[[$ Str1> $ str2], returns true if str1 is greater than str2

[[$ Str1 <$ str2], returns true if str1 is smaller than str2

[[-Z $ str] returns true if str is a Null String

[[-N $ str] returns true if str is a non-null string.

6 The test command can also be used to perform condition detection, which helps avoid too many parentheses.

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.