Linux Learning Nineth Lesson-shell script Programming

Source: Internet
Author: User
Tags aliases arithmetic

Linux Nineth session

--------------------------------------------------------------------------------------------------------------- -----------------

Program: algorithm + data structure

Data: The core of the program

Algorithm: How data is processed

Program Programming Style

Program: command-centric, data-serving instruction

Object type: Data-centric, instruction serves data

Advanced programming languages

Compile: advanced language → compiler → machine code → execute, e.g. c,c++, etc.

Explanation: Advanced language → execution → interpreter → machine code, e.g. Shell,python,php,javascript,perl, etc.

How to handle programming logic

Sequential execution, loop execution, select execution

Shell script: A text file that contains commands or declarations that conform to a certain format

Format requirements: #!/bin/bash (or other type of shell file, depending on the shell type used)

Shell scripting uses

Automating common commands

Perform system administration and troubleshooting

Create a simple application

Working with text or files

After writing a script, use chmoda+x to give it permission, and then put the script in the Bash folder or change $path or enter an absolute/relative path to execute, the script is an external command

Variable

Strongly typed: The variable is not cast, it is always the data type, and the implicit type conversion is not allowed. You must specify a type when defining a variable, a join operation must conform to a type requirement, and a call to declare a variable will produce an error

such as java,c#

Weak type: The runtime of the language implicitly does the data type conversion. 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 directly called without prior definition: Bash does not support floating-point numbers, PHP

Variable naming laws:

1 , you cannot make a reserved word in a program: for example If,for

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

3 , see the name of the known righteousness

4, unified naming rules: Hump naming law, such as small hump: Studentname, Big Hump studentname

Local variables: Variables can only be used in the current process, not for parent processes or child processes, name= "a"

Environment variable: A global variable that takes effect from itself and its child processes, cannot be used for the parent process, exportname= "a"

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

Position variable: $1,$2,... To indicate that the script is used to invoke parameters passed to it through the command line in the script code.

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

$? Determine whether the previous command succeeded or failed, no special designation, 0 for success, 1-255 for failure

The name of the foot

$* all parameters, parameters are an independent whole

[email protected] All parameters, parameters are independent individuals

$ #参数个数

$ number of number parameter

[Email protected]$* it only makes a difference when it's wrapped up in double quotes.

Shift:shift Key 1 times, the first parameter will not, before the second argument becomes the first parameter, the nth parameter becomes the n-1 parameter

$$ View command Current process

$PPID View the parent process of the current process

To enable the difference between a command source,., and bash

source/. Running the script does not turn on the child process, it affects the variables, and bash opens the subprocess without affecting the variables, all of which are normally used by bash activation scripts, unless the device needs to change the environment variable./source

Assigning values to variables

Variable assignment: name= ' value ', you can use reference value:

(1) can be a direct string; Name= "Root"

(2) Variable reference: name= "$USER"

(3) Order reference: Name= ' command ' name=$ (command)

Variable reference: ${name} $name

"": weak reference, where 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, while preserving the original string

Show all variables that have been defined: set

Delete variable: unsetname

Show all environment variables:

Env

Printenv

Export

Declare-x

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

Declaring read-only variables:

Readonlyname

Declare-rname

Viewing read-only variables: readonly–p

Positional variables: Calling parameters passed to the script through the command line in script code

set-- Clear all positional variables

Arithmetic operations

Arithmetic operations in bash: Helplet

+,-, *,/,% (take the remainder), * * (exponentiation)

To implement arithmetic operations:

(1) letvar= arithmetic expression

(2) var=$[arithmetic expression]

(3) var=$ (arithmetic expression)

(4) var=$ (Exprarg1arg2arg3 ...)

(5) Declare–ivar= value

(6) echo ' Arithmetic expression ' |BC

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

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

Random number between echo$[$RANDOM%50]:0-49

Assign value

Enhanced Assignment:

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

Letvaropervalue

Example: letcount+=3

Self-assignment after adding 3

Self-increment, self-reduction:

Letvar+=1

letvar++

Letvar-=1

letvar-

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 and

The first one is 0, and 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, and 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

Condition test

Determine whether a demand is satisfied, need to be implemented by the 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

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

&& represents conditional and then

|| Represents a conditional or ELSE

Test command

Examples of long formats:

Test "$A" = "$B" && echo "Strings is equal"

Test "$A"-eq "$B" && echo "integers is equal"

Examples of shorthand formats:

["$A" = "$B"] && echo "Strings is equal"

["$A"-eq "$B"] && echo "Integers is equal"

Bash's numerical test

-V VAR

Variable var is set

Numerical test:

-GT is greater than

-ge is greater than or equal to

-eq is equal to

-ne is not equal to

-lt is less than

-le is less than or equal to

Bash's string test

String test:

= is equal to

> 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 [[]]; extended regular expressions

-Z "string" string is empty, empty is true, not empty is false

-N "string" string is not empty, not empty is true, empty is false

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

Bash's file test

Presence Testing

-a FILE: Same-E

-e File: Test for existence of files, existence is true, otherwise false

Presence and category Testing

-B File: Exists and is a block device file

-C file: exists and is a character device file

-D file: Exists and is a catalog file

-F file: exists and is a normal file

-H file or-L file: Existing and Symbolic link files

-P file: exists and is a named pipe file

-S file: exists and is a socket file

File permission test:

-R FILE: exists and is readable

-W FILE: exists and is writable

-X FILE: exists and is executable

File Special Permissions Test:

-U FILE: Exists and has suid permissions

-G FILE: Exists and has Sgid permissions

-K FILE: Exists and has sticky permissions

File size test:

-S FILE: exists and is not empty

Whether the file is open:

-T FD:FD file descriptor is already open on a terminal

-N File: Whether the file has been modified since the last time it was read

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

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

Binocular test:

File1-ef file2:file1 is a hard link to FILE2

File1-nt File2:file1 is new to FILE2 (Mtime)

File1-ot File2:file1 is older than FILE2

Combination Test conditions for bash

The first way:

COMMAND1 && COMMAND2 and

COMMAND1 | | COMMAND2 or

! COMMAND Non-

Example: [[-R File]] && [[-W file]]

The second way:

Expression1-a EXPRESSION2 and

Expression1-o EXPRESSION2 or

! EXPRESSION

You must use the test command to

Use read to assign input values to one or more shell variables

-p Specifies the prompt to display

-s silent input, commonly used for passwords

n n Specifies the character length of the input

-d ' character ' input terminator

-T n timeout is n seconds

Read reads values from standard input, assigns a variable to each word

All remaining words are assigned to the last variable

Read-p "Enter a filename:" FILE

Dividing the command line into a single command word

Expand aliases

Expanded curly brace declaration ({})

Expand Tilde Declaration (~)

command to replace $ () and ')

Divide the command line into command words again

Expand File Wildcard (* 、?、 [ABC], etc.)

Prepare for i/0 redirection (<, >)

Run command

Prevent scaling

A backslash (\) causes subsequent characters to be interpreted as intended

$ echo Your Cost: \$5.00

Your Cost: $5.00

Quotation marks to prevent extension

Single quotation mark (') prevents all extensions

Double quotation marks (") also prevent all extensions, but the following exceptions apply:

? $ (dollar sign)-variable extension

? ' (anti-quote)-command substitution

? \ (backslash)-prohibit single character extension

?! (exclamation mark)-Historical command substitution

Bash's configuration file

In terms of effective scope, there are two categories:

Global configuration:

/etc/profile

/etc/profile.d/*.sh

/etc/bashrc

Personal configuration:

~/.bash_profile

~/.bashrc

Shell Login Two ways

Interactive login:

(1) Enter the account password directly through the terminal login

(2) Users who switch with "Su-username"

Order of execution:/etc/profile---/etc/profile.d/*.sh---~/.bash_profile--~/.BASHRC---/ETC/BASHRC

Non-interactive logon:

(1) Su UserName

(2) The terminal opened under the graphical interface

(3) Execute script

(4) Any other bash instance

Order of execution: ~/.BASHRC-/ETC/BASHRC-/etc/profile.d/*.sh

Profile class

By function, there are two categories:

Profile class and BASHRC class

Profile class: Provides configuration for the interactive logon shell

Global:/etc/profile,/etc/profile.d/*.sh

Personal: ~/.bash_profile

Function:

(1) for defining environment variables

(2) run a command or script

BASHRC class

BASHRC class: Provides configuration for non-interactive and interactive logon shells

Global:/ETC/BASHRC

Personal: ~/.BASHRC

Function:

(1) Defining command aliases and functions

(2) Defining local variables

Editing the configuration file takes effect

After you modify the profile and BASHRC file, it takes effect

Two methods:

1 restarting the shell process

2. or source

Bash quits task

Save in ~/.bash_logout file (user)

Run when you exit the login shell

For

Create an automatic backup

Clear Temporary files

$-variable

H:hashall, when this option is turned on, the shell hashes the path where the command is located, avoiding querying every time. The h option is turned off via set +h

I:interactive-comments, including this option, shows that the current shell is an interactive shell. The so-called interactive shell, in the script, I option is off.

M:monitor, open monitoring mode, you can control the process through the job to stop, continue, background or foreground execution.

B:braceexpand, curly brace extension

The H:history,h option opens, you can expand the commands in the History list, and you can do so by! Exclamation marks, such as "!!" Returns a recent history command, "!n" returns the nth historical command


Linux Learning Nineth Lesson-shell script Programming

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.