Shell script summary and tips in script writing

Source: Internet
Author: User

This article mainly summarizes the entry-level bash from the following aspects:

1. Command history and command completion

2. Pipelines and redirection

3. Command alias and command replacement

4. Edit the command line

5. File Name Configuration

6. Bash configuration files and variables

7. Programming (condition judgment and loop control)

8. array in bash

9. shell programming skills and programming specifications

 

 

1. Command history and command completion

 

View command history: history

-C: Clear command history

-D OFFSET [n]: Command to delete a specified position

-W: saves the command history to historical files, which is useful for executing commands on different terminals.

 

Usage tips for command history:

! N: The Nth command in the execution history;

! -N: The last n commands in the command history;

!! : Execute the previous command;

! String: the most recent command in the execution history that starts with a specified string.

! $: Reference the last parameter of the previous command;

Esc ,.

Alt +.

 

Command completion and path completion

Command completion: searches for executable files starting with the given string in each PATH specified by the PATH environment variable. If there is more than one executable file, two tabs can be provided; otherwise, it will be supplemented directly;

Path completion: Search for each file name in the given starting path and try to complete it;

 

 

2. Pipelines and redirection

 

Pipeline ------ the output of the previous command as the input of the next command

Command 1 | command 2 | command 3 |...

For example: cat/var/log/message | less

Find./-name ex * | xargs mv/backup

 

> Overwrite output

> Append output

2> redirect error output

2> append Mode

&> Redirect standard output or error output to the same file

<Input redirection

<Here Document

:> File: clears a file.

 

For example, Here Document:

Cat>/etc/hosts <EOF

172.28.9.45www01.opsmysql.com

172.28.9.46www02.opsmysql.com

172.28.9.47www03.opsmysql.com

172.28.9.48www04.opsmysql.com

EOF

 

"*/5 *****/usr/sbin/ntpdate ntp. api. bz>/dev/null 2> & 1

/Dev/null 2> & 1: redirects all standard output and error output to/dev/null.

 

 

3. Command alias and command replacement

Command alias

Alias = 'COMMAND [options] [arguments]'

The alias defined in shell is valid only in the current shell lifecycle; the alias is valid only for the current shell process;

 

Ualias same alias

 

For commands for setting aliases, if you want to use the command format when no alias is set, that is, the default format can be added before the command :\

\ CMD

 

You can also write the alias in the configuration file:

Global configuration file:/etc/bashrc

User Configuration File :~ /. Bashrc

 

COMMAND replacement: $ (COMMAND), reverse quotation marks: 'command'

Replace a sub-command with the execution result.

For example:

Echo "The date time is: 'date '"

Echo "The date time is: $ (date + % F )"

 

Quotes supported by bash:

'': Command replacement

": Weak reference, can replace variables

'': Strong reference. variable replacement is not completed.

 

4. Edit the command line

Cursor jump:

Ctrl + a: Jump to the beginning of the command line

Ctrl + e: jump to the end of the command line

Ctrl + u: Delete the content from the cursor to the beginning of the command line

Ctrl + k: Delete the content from the cursor to the end of the command line

Ctrl + l: clear screen

 

5. wildcard file name: globbing

 

*: Any character of any length

? : Any single character

[]: Match any single character in the specified range

[Abc], [a-m], [a-z], [A-Z], [0-9], [a-zA-Z], [0-9a-zA-Z]

[: Space:]: white space

[: Punct:]: punctuation

[: Lower:]: lowercase letter

[: Upper:]: uppercase letters

[: Alpha:]: uppercase/lowercase letters

[: Digit:]: Number

[: Alnum:]: Numbers and uppercase/lowercase letters

 

# Man 7 glob

[^]: Match any single character out of the specified range

 

[[: Alpha:] * [[: space:] * [^ [: alpha:]

 

6. Bash-related configuration files and variables

 

Bash configuration file:

Global Configuration

/Etc/profile,/etc/profile. d/*. sh,/etc/bashrc

Personal Configuration

~ /. Bash_profile ,~ /. Bashrc

 

Profile files:

Set Environment Variables

Run commands or scripts

 

Bashrc files:

Set local variables

Define command alias

 

How does the login shell read the configuration file?

/Etc/profile -->/etc/profile. d/*. sh --> ~ /. Bash_profile --> ~ /. Bashrc -->/etc/bashrc

 

How does a non-Login shell configure files?

~ /. Bashrc -->/etc/basrc -->/etc/profile. d/*. sh

 

Introduction to environment variable commands:

1. echo shows the value of an environment variable echo $ PATH

2. Set a new environment variable export HELLO = "hello" (no quotation marks are allowed)

3. env display all environment variables

4. set: Display locally defined shell Variables

5. unset clear environment variable unset HELLO

6. Set readonly to readonly.

 

Common Environment Variables

PATH: determines the directories to which shell will look for commands or programs.

HOME: HOME Directory of the current user

MAIL: refers to the MAIL storage directory of the current user.

SHELL: The Shell used by the current user.

HISTSIZE: the number of records that save historical commands.

LOGNAME: The Login Name of the current user.

HOSTNAME: indicates the host name. If a host name is used by many applications, it is usually obtained from this environment variable.

LANG/LANGUGE: language-related environment variable. Users in multiple languages can modify this environment variable.

PS1: is a basic prompt. For root users, it is # And for common users, it is $

PS2: A subsidiary prompt. The default value is "> ". You can modify the environment variable to modify the current command string.

 

 

Location variable:

$1, $2,... $ n

 

Special variables:

$? : Return Value of the execution status of the previous command. If the echo $0 result is 0, it indicates success, and if it is not 0, it indicates failure.

$0: get the name of the currently executed shell script file, usually used in combination with basename

$ *: Get all parameters of the current shell, $1 $2 $3. Note the difference with $ #.

$ #: Get the total number of parameters in the Current shell Command Line

$: Get the current shell process ID (PID)

$! : PID for executing the previous command

$ @: All parameters of this program "$1" "$2" "$3 ""... "

 

Note: Sometimes the variable name is easy to confuse with other words. For example, we Append content to the value of a variable:

Num = 2

Echo "this is the $ numnd"

This does not print "this is the 2nd", but only prints "this is the", because shell will search for the value of the variable numnd, but there is no value for this variable. We can use curly braces to tell shell that we want to print the num variable:

Num = 2

Echo "this is the $ {num} nd"

This will print: this is the 2nd

 

The variable name cannot start with a number !!!!!!!!!!!!!!!!

 

++ ++

How to perform arithmetic operations in shell:

A = 3

B = 6

1) let arithmetic expression

Let C = $ A + $ B

2). $ [arithmetic expression]

C = $ [$ A + $ B]

3). $ (arithmetic expression ))

C =$ ($ A + $ B ))

4). expr arithmetic expression. There must be spaces between the operands and operators in the expression, and a command reference should be used.

C = 'expr $ A + $ B'

 

These computing methods are the basis of shell programming !!!

 

 

Simple operations on strings in shell:

String Length

A = "admin"

Echo $ {$ A} Or expr length $

 

String replacement and deletion:

$ {Variable # keyword} ---------> If the variable content conforms to the 'keyword' from the beginning, the compliant shortest data will be deleted.

Example: echo

 

$ {Variable ## keyword} ---------> If the variable content conforms to the 'keyword' from the beginning, the longest matched item is deleted.

 

$ {Variable % keyword} ---------> If the variable content from the end to the forward matches the 'keyword', delete the compliant shortest data

 

$ {Variable % keyword} ---------> If the variable content conforms to the 'keyword' from the end, the longest matched item is deleted.

 

$ {Variable/old string/new string} ---------> If the variable content conforms to the 'old string', the first old string is replaced by the new string.

 

$ {Variable // old string/new string} ---------> If the variable content conforms to the 'old string', all old strings will be replaced by new strings.

 

 

7. Programming (condition judgment and loop control)

 

The following is a summary of the condition test types.

Integer Test

Character Test

File Test

 

Conditional test expression:

[Expression]

[[Expression] ----- in Bash High Version, basically only this advanced one can be used... the above one will report an error!

Test expression

 

Integer comparison:

-Eq: test whether two integers are equal. For example, $ A-eq $ B.

-Ne: test whether two integers are unequal. They are not equal to true. They are equal to false;

-Gt: test whether a number is greater than the other. If the value is greater than, the value is true. Otherwise, the value is false;

-Lt: test whether one number is smaller than the other. If the value is smaller than, the value is true. Otherwise, the value is false;

-Ge: greater than or equal

-Le: less than or equal

 

Logical Relationship:

Logic and :&&

When the first condition is false, the second condition does not need to be judged and the final result already exists;

When the first condition is true, the second condition must be judged;

Logic or: |

 

Note: [condition 1-a condition 2] is equivalent to [condition 1] & [condition 2]

 

Note the following:

Yes

[[Condition 1 & condition 2]

No

[Condition 1 & condition 2]

 

Character test:

=: Whether the test is equal, equal to true, not equal to false

! =: Whether the test is unequal. The value is not true. The value is false.

\>

\ <

-N string: test whether the specified string is null. If it is null, it is true. If it is not null, it is false.

-Z string: test whether the specified string is null. If it is null, it is false. If it is null, it is false.

String = "" the string is empty.

String! = "" The string is not empty.

 

 

File test:

-E FILE: whether the test FILE exists

-F FILE: test whether the FILE is a normal FILE

-D FILE: test whether the specified path is a directory.

-S FILE: determines whether the FILE exists and the size is greater than 0

-R FILE: test whether the current user has the permission to read the specified FILE.

-W FILE: indicates whether the FILE can be written.

-X FILE: indicates whether the FILE is executable.

 

 

Simply put, the script exit status code

 

Exit: exit the script.

Exit #

If the script does not clearly define the exit status code, the exit code of the Last Command executed is the exit status code of the script;

Generally:

#0 indicates normal exit

# Non-0 indicates an error exits

 

++ ++

Condition Determination -- if

Single branch if statement

If judgment condition; then

Statement1

Statement2

...

Fi

 

If statement for dual Branch:

If judgment condition; then

Statement1

Statement2

...

Else

Statement3

Statement4

...

Fi

 

Multi-branch if statement:

If condition 1; then

Statement1

...

Elif judgment condition 2; then

Statement2

...

Elif judgment Condition 3; then

Statement3

...

Else

Statement4

...

Fi

 

++ ++

Select Structure -- case

Case SWITCH in

Value1)

Statement

...

;;

Value2)

Statement

...

;;

*)

Statement

...

;;

Esac

 

 

Description: value1) is a regular expression style. The following characters can be used:

* String of any length

C * Indicates a string starting with C.

? Any single character ,???? A four-character string

[Abc] a, B, or c, for example, [abc] 123, matching a123, b123, or c123.

[A-n] any character from a to n

| Multiple choice, Separator

 

++ ++

Loop Control ---

Two usage methods:

For variable in list; do

Loop body

Done

 

For (expr1; expr2; expr3); do

Loop body

Done

 

 

Loop Control --- while

While CONDITION; do

Statment

Done

Enter the cycle: the condition is met

Exit loop: the condition is not met.

 

Special usage of while 1 (endless loop ):

While:; do

Statment

Done

 

Special usage of while 2 (Reading rows from a file ):

While read LINE; do

Statment

Done </PATH/TO/SOMEFILE

 

Method 2:

Cat ip.txt | while read line

Do

Echo $ line

Done

 

Loop Control ---

Until is opposite to while. You can refer to while

Until CONDITION; do

Statement

...

Done

 

Determine whether the condition is true. If the condition is not true, execute the loop body. If the condition is true, exit!

 

 

Loop Control statement

Break

Interrupt the loop, and then execute the statement following the loop. By default, the loop jumps out of a layer. to jump out of a multi-tier loop, you can use break n (n is a number greater than 1, that is, the number of times ).

Continue

Interrupt the current cycle and enter the next cycle in advance. A loop is skipped by default. If you want to skip multiple cycles, you can use continue n (n is a number greater than 1, that is, the number of times ).

 

++ ++

Select (generate menu selection)

A select expression is a bash extension application that is especially good at interactive use. You can select from a group of different values.

The select command can be used to create a simple list. The structure is similar to the for loop. It is generally used in combination with the case statement.

Write an instance as follows:

#! /Bin/bash

Echo "What is your favorite OS? "

Select var in "Linux" "Gnu Hurd" "Free BSD" "Other"; do

Break

Done

Echo "You have selected $ var"

 

 

8. Use arrays in bash

Array assignment method:

(1) array = (var1 var2 var3... varN)

(2) array = ([0] = var1 [1] = var2 [2] = var3... [n] = varN)

(3) array [0] = var1

Arrya [1] = var2

...

Array [n] = varN

 

Note: The subscript of the array in shell starts from 0 by default!

 

Obtain the number or length of array elements:

(1) $ {# array [@]}

(2) $ {# array [*]}

 

 

Display array elements:

Echo $ {array [*]} # Show all elements

Echo $ {array [@]}

Echo $ {array [@]: 0}

 

Echo $ {array [0]} # display the first element

 

Echo $ {array [@]: 2} # The first two elements in the array are not displayed.

Echo $ {array [@]: 0: 2} # display two elements starting from the first element

 

 

Delete elements from the array:

Unset array [2] # Delete the third element

Unset array # Delete the entire array

 

 

Delete a substring:

Echo $ {array [@] # t * e} # Start the shortest match on the left: "t * e", which matches "thre"

Echo $ {array [@] # t * e} # The longest match from the left, which matches "three"

Echo $ {array [@] % o} # minimum match starting from the end of the string

Echo $ {array [@] % o} # longest match starting from the end of the string

 

Substring replacement:

Echo $ {array [@]/o/m} # The first matched string will be deleted.

Echo $ {array [@] // o/m} # All matched items will be deleted.

Echo $ {array [@] // o/} # If no substring is specified, the matched substring is deleted.

Echo $ {array [@]/# o/k} # Replace the pre-String Terminal string

Echo $ {array [@]/% o/k} # Replace the string with the terminal string

 

 

List array elements cyclically:

#! /Bin/bash

Arr = (AB bc cd)

Lenarr =$ {# arr [@]}

For (I = 0; I <$ lenarr}; I ++); do

Echo $ {arr [$ I]}

Done

 

 

#! /Bin/bash

Arr = (AB bc cd)

Lenarr =$ {# arr [@]}

I = 0

While [[$ I-lt $ lenarr]

Do

Echo $ {arr [$ I]}

Let I ++

Done

 

One instance:

#! /Bin/bash

# Set IFS to set the delimiter to a line break (\ n)

OLDIFS = $ IFS

IFS = $ '\ N'

 

# Reading file content to an array

FileArray = ($ (cat file.txt ))

 

# Restore it

IFS = $ OLDIFS

TLen =$ {# fileArray [@]}

 

# Display the file content cyclically

For (I = 0; I <$ {tLen}; I ++); do

Echo "$ {fileArray [$ I]}"

Done

 

 

9. shell programming skills and programming specifications

 

Check Syntax: bash-n Script Name

Command tracing: bash-x Script Name

 

In shell input and output:

Read usage

Cat special usage

Special echo usage

 

Run the following command in the background: & nohup

If you are running a process that does not end when you exit the account, you can use the nohup command. This command can continue running the corresponding process after you exit the account. Nohup means no hang up ).

The nohup command is generally in the form of nohup command &

Shift usage

.......

.........

..........

Later!

Briefly describe the programming specifications:

1. File comments

Each written script file should contain file comments, simple descriptions of script usage, versions, authors, etc. .. For example:

 

#! /Bin/bash

# Description :.......

# Date: xxxx-xx

# Version :....

# Author: Andy

 

2. Code comments

3. Function annotation -- describe the functions of the Function

 

4. variable naming Standardization

The name indicates the meaning of the variable.

Variable name or function name should not be too long

Name should start with uppercase or uppercase

For example:

Passwd

Num_Count

 

5. Code indentation

 

Original works can be reprinted. During reprinting, you must mark the original source, author information, and this statement in hyperlink form. Otherwise, legal liability will be held.

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.