8.11_linux bash Shell scripting Getting Started (i)

Source: Internet
Author: User
Tags arithmetic

What is Bash shell script programming?

A: There are multiple shells in Linux, and the default shell for CentOS and Redhat is the bash shell. As for shell scripts, this is a bit like (. bat file) for batch files inside the Windows operating system. I wonder if you remember the philosophical thinking of Linux? There are two points: a single application consisting of a multitude of purposes: A program that only does one thing and does it well; a single small program that combines purpose to accomplish complex tasks . I think shell scripting is a good embodiment of this philosophical idea. Shell scripting takes advantage of the shell's function abbreviation for a "program" that uses a plain text file that writes some shell syntax and commands (internal commands and external commands) inside, with regular expressions, pipeline commands, and data flow redirection to achieve the desired processing purpose.


What is the use of shell scripts?

The uses of shell scripts are:

Automating common commands

Perform system administration and troubleshooting

Create a simple application

Working with text or files


BASIC Programming Concepts

How to handle the programming logic:

Sequential execution

Loop execution

Select Execute


Shell programming: procedural, interpreting execution

The basic structure of the programming language:

Data storage: variables, arrays

Expression: A + b

Statement: If


A shell script is a text file that contains some commands or declarations and conforms to a certain format

Format requirements: First line shebang mechanism

#!/bin/bash


Good habits of shell programming

It is necessary to develop good shell programming habits, if you want to ask why? You can think about it. If you have just entered a company, take over the job, and then let you execute some scripts or let you change. If someone else does not have a little comment, do you see the code at the first glance will be dumbfounded? If the code is hundreds or thousands of lines, if you do not understand the situation to modify, it is not equivalent to write a script again? What a waste of time and energy. Even if you look at your own script, it is not even in the future maintenance of the time you forget. So, a good programming habit is a must.

For example, some examples:

Some basic information such as the author information of the script, the version of the script, the role of the script, the function of some code, etc.

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M02/85/EF/wKiom1ev6FrADLyrAABTLuxxC6E985.png "title=" 2.png " alt= "Wkiom1ev6fradlyraabtluxxc6e985.png"/>


Script debugging

When we finish writing a script, there are a lot of times when it's hard to make a small mistake. So after writing the script, you need to check the script for syntax errors and so on.


Bash-n script.sh

Detect syntax errors in scripts


For example, if the script does not have errors, execute the command without prompting

If the script has a syntax error, see the first execution of the bash-n below. This will be an error.

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M00/85/EF/wKioL1ev6zywC6OPAAA-IQUUWwc208.png "title=" 3.png " alt= "Wkiol1ev6zywc6opaaa-iquuwwc208.png"/>


Bash-x/path/to/some_script

Debug scripts


For example, when debugging the script, he will show the steps to execute the script, if there is an error, we can find out in time where there is a problem and correct it.

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M00/85/EF/wKiom1ev7sPjVsJXAABIK0gRKfA265.png "title=" 4.png " alt= "Wkiom1ev7spjvsjxaabik0grkfa265.png"/>



The variables in bash


What is a variable?

Variable: named memory space

How variable data is stored:

Character:

Value: Integer, floating-point


the role of variables

1. Data storage format

2, the operation of the participation

3, the data range indicated


Programming languages are divided into strongly typed and weakly typed languages

Strong type:

You must specify a type when defining a variable, a join operation must conform to a type requirement, and calling an undeclared variable produces an error

such as Java,python

Weak type:

You do not need to specify a type, the default is character type, the participating operation will automatically do the implicit type conversion, the variable can be called directly without prior definition

For example: Bash does not support floating-point numbers


The law of Variable nomenclature

1. The reserved words in the program cannot be made: for example if, for;

2, only use numbers, letters and underscores, and cannot start with a number

3, see the meaning: If the result of addition, with sumplus and so easy to see

4, unified naming rules: Hump naming method (such as Sumplus, try not to use plain lowercase or pure capitalization to avoid conflicts with other variables of the system)


Types of variables

Based on criteria such as the scope of the variable's entry:

Local variable: The active scope is the current shell process and is not valid for Shell processes other than the current shell, including the current Shell's child shell process

Environment variable: The active scope is the current shell process and its child processes

Local variables: The effective range is a snippet of code in the current shell process (usually referred to as a function)

Positional variables: $, $, ... To indicate that the script is used to invoke parameters passed to it through the command line in the script code.

Special variables: $?, $, $*, [email protected], $#


Here's an example to illustrate these variable effects:


Local variables: (This means like a personal setting)


Assignment format name= ' value '

Value can use references:

1. Can be direct character channeling; Name= "username"

2. Variable reference: Name "username"

3. Command reference name= ' command ', name=$

Variable reference: $name, ${name}

"": a weak reference in which the variable reference is replaced with the value of the variable;

": Strong reference, where the variable reference is not replaced with the value of the variable, and the original string is persisted;

Show all local variables that have been defined: set

Destroy variable: unset name


Can see alias inside this administrator user and ordinary user alias inside the settings are a bit different, this is the local variable

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M01/85/EF/wKioL1ewBRHB6bBqAAAWMGcjMPk027.png "style=" float: none; "title=" 5.png "alt=" Wkiol1ewbrhb6bbqaaawmgcjmpk027.png "/>

650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M02/85/F0/wKiom1ewBRKSDdzyAAAYbTKYbhI679.png "style=" float: none; "title=" 6.png "alt=" Wkiom1ewbrksddzyaaaybtkybhi679.png "/>


Environment variables: (The state laws, so-called national rules, we have to abide by, which is understood as environment variables)


Variable declaration, assignment: Export name=value or Declare-x Name=value

Variable reference: $name, $ (name)

Show all environment variables: export, env, printenv

Destroyed: unset name


Bash has many built-in environment variables: such as path, Histsize, PS1, and so on.

as follows, when you use an external command, you are using the environment variable specified by path to search for the location of the command.

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M00/85/F0/wKioL1ewCE3BFrBzAAAVZR3LEfQ680.png "title=" 7.png " alt= "Wkiol1ewce3bfrbzaaavzr3lefq680.png"/>


Positional variables: (in the script with $ $, $ $, $n, Shift [n], the variable represented by position)


Assignment: Script $1,$2,... corresponding to call 1th, 2nd, and other parameters;

For example, the assignment is 1,$2 to 10 and computes the and of 1 to 10 of all integers.

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/85/F0/wKioL1ewG6CxhORdAABtPeHuJlg814.png "title=" 8.png " alt= "Wkiol1ewg6cxhordaabtpehujlg814.png"/>

However, this position variable is interesting, after the parameters of more than 10, the 10th parameter will be in the form of a parameter of $ (0), I do not understand what this means. If the first parameter is a, then the 10th start, the tenth variable shows the A0, 20th is B0, 30th is c0 and so on ...

650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M01/85/F0/wKioL1ewIoeyhizZAAAZdXZ5Vos835.png "title=" 9.png " alt= "Wkiol1ewioeyhizzaaazdxz5vos835.png"/>


Special variables: $?, $, $*, [email protected], $#


$?, which indicates the return status of the command execution, 0 indicates success, not 0 is failed, as shown in

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/85/F0/wKioL1ewHe6BydLFAAAsVTWAkfM638.png "title=" 10.png "alt=" Wkiol1ewhe6bydlfaaasvtwakfm638.png "/>


$ A, which means the command itself

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M00/85/F0/wKioL1ewHoXgg7P6AAAfZld_zDc204.png "title=" 11.png "alt=" Wkiol1ewhoxgg7p6aaafzld_zdc204.png "/>


$#: How many parameters are passed to the script, if there are two parameters, then $#=2, as shown, if $ #的参数不等于2, then the script prompts "Please output the correct address parameters."

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M01/85/F0/wKiom1ewH07TiS1IAAA-IBpL32g323.png "title=" 12.png "alt=" Wkiom1ewh07tis1iaaa-ibpl32g323.png "/>


$* and [email protected], these two, only have "" double quotation marks when will show the different meaning

$*: All parameters passed to the script

[email protected]: reference to all parameters passed to the script

For example, when $* with double quotes, $* represents ' a B C ', this is a whole, but without double quotes, is a and B and C

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/85/F0/wKioL1ewJKfjTm7tAABEHp4jeVY053.png "title=" 13.png "alt=" Wkiol1ewjkfjtm7taabehp4jevy053.png "/>


Read-only variables: can only be declared, but cannot be modified and deleted

Assignment: Readonlyname, declare-r name

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M00/85/F0/wKioL1ewKKCSGiuqAAAqew44qcQ864.png "title=" 14.png "alt=" Wkiol1ewkkcsgiuqaaaqew44qcq864.png "/>


Arithmetic operations in Bash


arithmetic operations in Bash : (Help-file see helping let)

+ (plus),-(minus), * (multiplied),/(divided),% modulus (remainder), * * (exponentiation)

To implement arithmetic operations:

(1) Let var= arithmetic expression

(2) var=$[arithmetic expression]

(3) var=$ (arithmetic expression)

(4) var=$ (expr arg1 arg2 arg3 ...)

(5) Declare–ivar= value

(6) echo ' Arithmetic expression ' | Bc

650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M00/85/F1/wKiom1ewLdniqK3aAABUcI9D5ZU608.png "title=" 16.png "alt=" Wkiom1ewldniqk3aaabuci9d5zu608.png "/>

Multiplication symbols need to be escaped in some scenarios, such as *

Bash has built-in random number generator: $RANDOM (1-32767)

echo $[$RANDOM%50]: Random number between 0-49, if 1-50 is required randomly, then $[$RANDOM%50]+1

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M01/85/F0/wKioL1ewLSXgoznfAAAdbo04TgA885.png "title=" 15.png "alt=" Wkiol1ewlsxgoznfaaadbo04tga885.png "/>



Assign value


Enhanced Assignment:

+=, -=, *=, /=, %=

Let Varopervalue

Example: Let count+=3

Self-assignment after adding 3

Self-increment, self-reduction:

Let Var+=1

Let var++

Let Var-=1

Let var--

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M01/85/F1/wKiom1ewLz7TwXBRAAAbeRhrNzI578.png "title=" 17.png "alt=" Wkiom1ewlz7twxbraaaberhrnzi578.png "/>


Logical operations


True, False

1, 0

And:

1 and 1 = 1

1 and 0 = 0

0 and 1 = 0

0 and 0 = 0

Or:

1 or 1 = 1

1 or 0 = 1

0 or 1 = 1

0 or 0 = 0

Non -:!

! 1 = 0

! 0 = 1


Short-circuit Operation:


Short Circuit with:

The first one is 0, the result must be 0;

The first one is 1, the second must be involved in the operation;

Short Circuit or:

The first one is 1, the result must be 1;

The first one is 0, the second must be involved in the operation;

XOR: ^

XOR two values, same as false, different for true


Gather command


There are two ways to gather commands:


Compound: date; W.H.O. | The WC-L command will run one after another,


Child Shell: (date; who | wc-l) >>/tmp/trace, all outputs are sent to a single stdout and stderr


650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/85/F2/wKiom1ewTW_iKuQIAAAi12mJlhQ577.png "title=" 19.png "alt=" Wkiom1ewtw_ikuqiaaai12mjlhq577.png "/>

Bash exit status code


Process uses exit status to report success or failure

0 stands for Success, 1-255 for failure

$? Variable saves the most recent command exit status

For example:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/85/F0/wKioL1ewHe6BydLFAAAsVTWAkfM638.png "title=" 10.png "alt=" Wkiol1ewhe6bydlfaaasvtwakfm638.png "/>


Bash Custom exit status code


Exit [n]: Custom exit status code;

Note: Once the exit command is encountered in the script, the script terminates immediately; the terminating exit state depends on the number following the Exit command

Note: If you do not specify an exit status code for the script, the exit status code for the entire script depends on the status code of the last command executed in the script

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/85/F1/wKioL1ewT1GgOWhnAABKMLYXcwg741.png "title=" 20.png "alt=" Wkiol1ewt1ggowhnaabkmlyxcwg741.png "/>


Condition test


To determine whether a demand is satisfied, it needs to be realized by testing mechanism;

A dedicated test expression needs to be assisted by a test command to complete the test process;

Evaluate Boolean declarations for use in conditional execution

If true, then return 0

If False, 1 is returned


Test command:

Test EXPRESSION

[EXPRESSION]

[[EXPRESSION]]

Note: You must have a white space character before and after expression


650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M00/85/F1/wKioL1ewT86QrHOVAAAWPjOvFA8555.png "title=" 21.png "alt=" Wkiol1ewt86qrhovaaawpjovfa8555.png "/>


Depending on the exit status, the command can be run conditionally

&& represents conditional and then

|| Represents a conditional or ELSE


For example, the parameter 1 must be less than the parameter 2, the condition is established,&& is calculated from the parameter 1 to the parameter 2 and the same, | | Otherwise, the hint parameter 1 must be less than parameter 2

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M01/85/F1/wKioL1ewMlCRGnTPAABIT4ijXPM118.png "title=" 18.png "alt=" Wkiol1ewmlcrgntpaabit4ijxpm118.png "/>


Test type of Bash


Numerical test:

-GT: Is it greater than;

-ge: is greater than or equal to;

-eq: Is it equal to;

-ne: is not equal to;

-LT: Is it less than;

-le: is less than or equal to;


For example, the parameter 1 must be-lt less than parameter 2, the condition is set to execute the && condition, otherwise, the hint parameter 1 must be-lt less than the parameter 2

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M01/85/F1/wKioL1ewMlCRGnTPAABIT4ijXPM118.png "title=" 18.png "alt=" Wkiol1ewmlcrgntpaabit4ijxpm118.png "/>


String test:

= =: whether equal;

ASCII code is greater than ASCII code

<: is less than

! =: is not equal to

=~: Whether the left string can be matched by the pattern on the right

Note: This expression is typically used in [[]];

-Z "string": whether the string is empty, empty is true, not empty is false

-N "string": whether the string is not empty, not empty is true, empty is false

Note: The operands used for string comparisons should all use quotation marks


650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M01/85/F1/wKioL1ewUBbiotwOAAAVpfhf94A294.png "title=" 22.png "alt=" Wkiol1ewubbiotwoaaavpfhf94a294.png "/>

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M01/85/F2/wKiom1ewUQCAE5iHAAAeUOA1rm0564.png "title=" 23.png "alt=" Wkiom1ewuqcae5ihaaaeuoa1rm0564.png "/>


File Presence Testing

-a FILE: Same-E

-E File: The existence of the test, the existence of the true, otherwise false;

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M00/85/F1/wKioL1ewUY2iksdVAAA0kElVgwI159.png "title=" 24.png "alt=" Wkiol1ewuy2iksdvaaa0kelvgwi159.png "/>


Presence and category Testing

-B File: Whether it exists and is a block of device files;

-C File: Existence and character device files;

-D file: exist and are directory files;

-F file: exists and is a normal file;

-H file or-L file: exists and is a symbolic link;

-P file: exists and is a named pipe file;

-S file: exists and is a socket file;


650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M01/85/F2/wKiom1ewUdmz15XgAAAsp5ULr_g796.png "title=" 25.png "alt=" Wkiom1ewudmz15xgaaasp5ulr_g796.png "/>


file permission Test :

-R FILE: exists and is readable

-W FILE: exists and is writable

-X FILE: exists and is executable


650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M02/85/F1/wKioL1ewU13Q5KszAABQfyocWBI404.png "title=" 26.png "alt=" Wkiol1ewu13q5kszaabqfyocwbi404.png "/>


File Special Permissions Test:

-G FILE: Exists and has sgid permissions;

-U FILE: Exists and has suid permissions;

-K FILE: Exists and has sticky permissions;


650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M00/85/F2/wKioL1ewVHGTsz0WAABGQAObgDU606.png "title=" 27.png "alt=" Wkiol1ewvhgtsz0waabgqaobgdu606.png "/>


File size Test :

-S FILE: exists and is not empty;


650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M00/85/F2/wKioL1ewVT2gUJe5AAAxQMyXRbQ004.png "title=" 28.png "alt=" Wkiol1ewvt2guje5aaaxqmyxrbq004.png "/>


Whether the file is open:

-T FD:FD indicates whether the file descriptor is open and related to a terminal

-N File: whether the files have been modified since the last time they were read (judging the file mainly depends on the change)

-O File: Whether the current active user is a file owner

-G file: whether the current active user is a group of files


650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M00/85/F2/wKiom1ewVrngr1RoAAAkrJWv2DY588.png "title=" 30.png "alt=" Wkiom1ewvrngr1roaaakrjwv2dy588.png "/>


Binocular test:

File1-ef whether File2:file1 and FILE2 point to the same inode on the same device

File1-nt File2:file1 is new to FILE2; (judging the file mainly depends on the modified time)

File1-ot File2:file1 is older than FILE2; (judging the file mainly depends on the modified time)


650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M00/85/F2/wKioL1ewV5SjHLoEAAAqaKxXT3w340.png "style=" float: none; "title=" 31.png "alt=" Wkiol1ewv5sjhloeaaaqakxxt3w340.png "/>

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/85/F2/wKiom1ewV5Xy4N9wAAA6lwL9LLE089.png "style=" float: none; "title=" 32.png "alt=" Wkiom1ewv5xy4n9waaa6lwl9lle089.png "/>


Combination test conditions

The first way:

COMMAND1 && COMMAND2 and

COMMAND1 | | COMMAND2 or

! COMMAND Non-

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M01/85/F2/wKiom1ewXi_RRZ6wAABPiJVtbSU258.png "title=" 35.png "alt=" Wkiom1ewxi_rrz6waabpijvtbsu258.png "/>

such as: [-e file] && [-R File]

The second way:

Expression1-a EXPRESSION2 and

Expression1-o EXPRESSION2 or

! EXPRESSION

650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M02/85/F2/wKiom1ewWLDhOVocAAA8Ehq4DL8468.png "title=" 33.png "alt=" Wkiom1ewwldhovocaaa8ehq4dl8468.png "/>

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M01/85/F2/wKioL1ewXJnA5vIhAAAtSPPTlLc351.png "title=" 34.png "alt=" Wkiol1ewxjna5vihaaatspptllc351.png "/>

This article is from the "~ Breeze ~" blog, please be sure to keep this source http://wanweifeng.blog.51cto.com/1957995/1837852

8.11_linux bash Shell scripting Getting Started (i)

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.