Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Basic script programming

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/03 Report--

Programming style procedure: instruction-centered, data serving instruction object: data-centered, instruction serving the execution of data programs computer: running binary instruction programming language: a language for human-computer interaction low-level programming language machines: binary sequences of 0 and 1, called machine instructions. Too different from natural language, difficult to understand and difficult to write assembly: replace machine instructions with some mnemonic symbols, called assembly language      such as: ADD APowerB put the number of register An and the number of register B into register A the program written by      assembly language needs to convert the assembly program into machine instruction      assembly language is slightly easier to understand, that is, the mnemonic corresponding to machine instructions. Mnemonic is more similar to natural language high-level programming language compilation: high-level language-- > compiler-- > machine code-- > execute      Czochralski +   interpretation: high-level language-- > execution-- > interpreter-- > machine code      shell,python,php,JavaScript,perlshell script

A text file that contains some commands or statements in a certain format

The format requires the first line to declare the sequence     #! / bin/bash to add comments     comments to run the script starting with #     gives the script execution permission to specify the absolute or relative path of the script on the command line     runs the interpreter directly The purpose of running shell scripts as a parameter of the interpreter program is to automate common commands, execute system management and troubleshooting, create simple applications to process text or file scripts, debug, detect syntax errors in scripts,    bash-n path debug execution

Bash-x path

Shell variable naming rule 1, can not make the reserved words in the program: for example, if, for2, can only use numbers, letters and underscores, and can not start with a number 3, see the name meaning 4, unified naming rules: hump naming method Shell naming suggestion rule 1, variable name capitalization 2, local variable lowercase 3, function name lowercase 4, in English name, and reflects the actual type of variable in bash

Classify the following variable types according to criteria such as the effective scope of the variable

Local variable: the effective scope is the current shell process; it is invalid for other shell processes other than the current shell, including the child shell process of the current shell

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

Local variable: the effective scope is a code snippet in the current shell process, usually referring to a function

Location variable: $1, $2,. To let the script call the parameters passed to it from the command line in the script code

Special variables: $?, $0, $@, $#, $$

The execution name of the program    $0

The nth parameter value of this program,    $n. 9. Denoted by ${n}

   $* all parameters passed to the script, all of which are combined into one string

The number of parameters of the program    $#

   $$PID of this program (ID number of the current process in which the script is running)

   $! The PID that executed the previous background instruction (the process ID number of the last process running in the background)

   $? The return value of executing the previous instruction (displays the exit status of the last command. 0 means there is no error, and any other value indicates an error)

   $- displays the current options used by shell, with the same functionality as the set command

   $@ is similar to $*, with all parameters passed to the script, each of which is a separate string

Local variable assignment: name='value' can use reference value   (1) can be a direct string: name= "root"   (2) variable reference: name= "$USER"   (3) command reference: name=COMMAND     name=$ (COMMAND) variable reference: ${name} or $name variable "" weak reference, where the variable reference will be replaced with the variable value   'strong reference, and the variable reference will not be replaced with the variable value Keep the original string

Show all defined variables: set

Delete variable: unset name

Environment variable declaration, assignment:    export name=VALUE    declare-x name=VALUE variable reference:    $name, ${name} display all environment variables:    env    printenv    export    declare-x delete the variable   unset name arithmetic operation bash: help let variable +, -, *, /,% take module (remainder),\ * (multiplier)    (1) let var= arithmetic expression    (2) var=$ [arithmetic expression]    (3) var=$ ((arithmetic expression))    (4) var=$ (expr arg1 arg2 arg3...)    (5) declare-I var= numeric    (6) echo 'arithmetic expression' | bcbash has a built-in random number generator variable: $RANDOM (0-32767) )    example: generate a random number between 0-49      echo $[$RANDOM%50] assignment enhanced assignment:    + = -=,\ * =, / =,% = let varOPERvalue   for example: let count+=3    since the addition of 3 since the    since the increment Self-subtraction:      let var+=1      let var++      let var-=1      let var-- logic operation

Rue,false

   1,0

And: &

   1 and 1

   1 and 0

   0 and 1: 0

  

Or: |

   1 or 1x 1

   1 or 0x1

   0 or 1x 1

   0 or 0: 0

Non:!

  ! 1: 0   ! true

  ! 031   ! false

XOR: ^

Two values of    XOR, the same is false, the different is true 

Short circuit operation

Short circuit and

The first    is 0, and the result must be 0

The first    is 1, and the second must participate in the operation.

Short circuit or

The first    is 1, and the result must be 1

The first    is 0, and the second must participate in the operation.

Example

Right is 1, error is 0

And operation:

Or operation

Not: inverted:

AB values are exchanged.

Short circuit and & &

Short circuit or | |

And & &:

Successfully continue to execute later

If you fail, you don't have to execute later.

Or | |:

Failure continues to be executed later, but success does not need to be executed later.

And or:

Conditional test

To judge whether a requirement is met, a special test expression needs to be implemented by a test mechanism, which needs to be assisted by test commands to complete the test process .

Evaluate Boolean declarations for use in conditional execution:

   returns 0 if it is true

If    is false, 1  is returned.

Test commands:

   test EXPRESSION

   [EXPRESSION]

   [[EXPRESSION]]

Note: there must be white space characters before and after EXPRESSION

Numerical Test of bash

-v VAR

Whether the    variable VAR is set

   example: determine whether the NAME variable is defined

  [- v NAME] 

Numerical test:

Whether the   -gt is greater than

Whether   -ge is greater than or equal to

Is   -eq equal to

Whether   -ne is not equal to

Whether   -lt is less than

Whether   -le is less than or equal to

String testing of bash

String test:

Whether the   -z "STRING" string is empty, true, or false

Whether the   -n "STRING" string is not empty, true or false

   = whether equal to > whether the ascii code is greater than the ascii code

Whether    < is less than

Whether   ! = is not equal to

   = = whether the string on the left is the same as the PATTERN on the right

   Note: this expression is used in [[]], where PATTERN is a wildcard.

   = ~ whether the string on the left can be matched by PATTERN on the right

   Note: this expression is used in [[]]; extended regular expression

File testing of Bash

Existence test

  -a FILE: same as-e

  -e FILE: file existence test, existence is true, otherwise it is false 

Existence and category testing

  -b FILE: whether it exists and is a block device file

  -c FILE: whether it exists and is a character device file

  -d FILE: whether it exists and is a directory file

  -f FILE: whether it exists and is a normal file

  -h FILE or-L FILE: exists and is a symbolic link file

  -p FILE: whether it exists and is a named pipe file

  -S FILE: whether it exists and is a socket file

File permission Test of Bash

File permission test:

  -r FILE: whether it exists and is readable

  -w FILE: whether it exists and is writable

  -x FILE: whether it exists and executable 

File Special permissions Test:

  -u FILE: whether it exists and has suid permission

  -g FILE: whether it exists and has sgid permission

  -k FILE: whether it exists and has sticky permission

File attribute Test of Bash

File size test:

  -s FILE: whether it exists and is not empty 

Whether the file is open:

  -t fd: whether the fd file descriptor has been opened on a terminal

  -N FILE: whether the file has been modified since it was last read

  -O FILE: whether the current valid user is the file owner

  -G FILE: whether the current valid user is a file group

Binocular test:

   FILE1-ef FILE2: whether FILE1 is a hard link to FILE2

   FILE1-nt FILE2: whether FILE1 is new than FILE2 (mtime)

   FILE1-ot FILE2: whether FILE1 is older than FILE2

Combinatorial test conditions for Bash

The first way:

   [EXPRESSION1-an EXPRESSION2] and

   [EXPRESSION1-o EXPRESSION2] or

   [! EXPRESSION] reverse

  -an and-o need to be done with test commands, and [[]] does not support 

The second way:

   COMMAND1 & & COMMAND2 and, short circuit and, represent conditional AND THEN

   COMMAND1 | | COMMAND2 or short circuit, which represents conditional OR ELSE

  ! COMMAND is not

   example:

   [- f "$FILE"] & & [["$FILE" = ~. *\ .sh$]]

Example:

Test:

[]:

Determine the user magedu: output the result if it exists, create the user and output the result if it does not exist

Determine the user wang: output the result if it exists, create the user and output the result if it does not exist

[[]]: regular expressions, wildcards are supported

= is followed by an extended regular expression

= is followed by a wildcard

Find the file at the end of .log / .xlog and output the result

If the file hello.sh is suffixed with .sh, add execute permission

If the hello.txt file is a .sh suffix, add execute permissions, if not, do not add

Look at the file hello.txt is a .sh suffix or a .txt suffix

-gt-a-o-lt:

Judge whether the value of n is greater than or equal to 90 and less than or equal to 100; judge whether the value of n is greater than or equal to 90 or less than or equal to 100

-f-a-r: determine whether / etc/issue is a file and is readable

Practice

Write a script hostping.sh that accepts the IPv4 address of a host as a parameter to test whether it can be connected. If ping is accessible, the user is prompted that the IP address is accessible; if the ping address is not accessible, the user is prompted that the IP address is inaccessible

Write a script checkdisk.sh to check the disk partition space and inode utilization. If it exceeds 80%, send an email warning that the space will be full.

Write scripts nologin.sh and login.sh to prohibit and allow ordinary users to log on to the system

Prohibit:

Allow:

Use the read command to accept input

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

Common option

-p specifies the prompt to display

-s silent input, generally used for passwords

-n N specifies the character length N entered

-d 'character' input Terminator

-t N TIMEOUT is N seconds

Read reads values from standard input and assigns a variable to each word. All remaining words are assigned to the last variable.

Read-p "Enter a filename:" FILE

Example:

Read-p: specify the prompt to display

Read-sp: hides the password entered

Read-n: take only the first three characters

Read-d: ends when you see the specified character

Read-t: in seconds. If you do not lose the timeout, you will exit directly.

Practice

Write a script hostping.sh that lets the user enter IP to test whether it is reachable. If ping is accessible, the user is prompted that the IP address is accessible; if the ping address is not accessible, the user is prompted that the IP address is inaccessible

Conditional selection if statement

Optional execution: 

Note: if statements can nest 

Single branch

   if judgment condition; then

Branch code whose      condition is true

   fi 

Double branch

   if judgment condition; then

Branch code whose      condition is true

   else

Branch code with false      condition

   fi

Multiple branches

   if judgment condition 1; then

Branch code where      condition 1 is true

   elif judgment condition 2; then

Branch code where      condition 2 is true

   elif judgment condition 3; then

Branch code where condition 3 of      is true

   else

Branch code where the above conditions of      are all false

   fi 

Judge by condition, execute its branch when the first encounter is "true" condition, and then end the entire if statement

Practice

Double branch

Write a script IP to prompt the user that it is inaccessible, and if it is not an illegal IP, it can be accessed.

Multiple branches

Write a script to measure your body mass according to BMI

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report