当前位置:网站首页>Shell script -- shell programming specification and variables

Shell script -- shell programming specification and variables

2022-04-23 16:57:00 Kiro Jun

One 、Shell Script Overview

1.1.1 Shell Basic concepts

  • Save the commands to be executed in order to a text file
  • Give the file executable permissions
  • It can combine all kinds of Shell Control statements to perform more complex operations

1.1.2 Shell Script application scenarios

  • Repetitive operations
  • Interactive tasks
  • Batch transactions
  • Service running status monitoring
  • Scheduled task execution

1.1.3 Shell effect —— The interpreter

shell It's a special application , It lies between the operating system kernel and the user , Acting as a “ command interpreter ” Role , Be responsible for receiving and interpreting the operation instructions input by the user , Pass the operation to be performed to the kernel for execution , And output the execution result .
echo command

Two 、shell Programming specification

2.1 The user login shell

  • After logging in, the default shell Program , It's usually /bin/bash
  • Different shell The internal instructions of 、 The operating environment will be different
     Insert picture description here
shell explain
bash $ Base on GNU Developed under the framework of shell
csh The grammar is a bit similar to C Linguistic shell
tcsh Integrated csh, More features ( Enhanced version )
sh Has been bash Replaced by ( Soft link )
nologin strange shell, This shell It can prevent users from logging in to the host

2.2 shell The composition of the script

  • Script statement ( Interpreter ): If the first act “#!/bin/bash”, Indicates that the code statement below this line is passed /bin/bash Program to execute ,#!/bin/bash Is the default interpreter , There are other types of interpreters , such as #!/usr/bin/python、#!/usr/bin/expect.
  • Annotation information : With “#” The opening statement is expressed as a comment message , The annotated statement will not be executed when the script is run .
  • Executable statement : such as echo command , For output “ ” String between .

 Insert picture description here

2.3 shell How to execute the script

Method 1 : Command to specify the path , It is required that the document must have x jurisdiction

  • Specify the absolute path :/root/first.sh
  • Specify the relative path :./first.sh

 Insert picture description here

Method 2 : Appoint shell To explain the script , It is not required that the document must have x jurisdiction

  • sh Script path :sh first.sh
  • source Script path :.first.sh perhaps source first.sh
     Insert picture description here

Method 3 :source Script path execution shell Script
 Insert picture description here

2.4 Script error

Wrong command : Command error will not affect the next command to continue

Grammar mistakes : Will affect the next command to continue

Logic error : You can only screen yourself

 Find the correct code :

bash -n  Script name  ( Do not add an absolute path to the current directory )    Check for grammatical errors 
bash -x  Script name  ( Do not add an absolute path to the current directory )    Check for logic errors 

2.5 Redirect

Interactive hardware devices

The standard input : Receiving data input from the user from the device
standard output : Output data to the user through the device
The standard error : Report execution error information through this device

type Device file Document description number Default device
The standard input /dev/stdin 0 keyboard
standard output /dev/stdout 1 Monitor
Standard error output /dev/stderr 2 Monitor

Redirection operation

type operation purpose
Redirect input < Read data from the specified file
Redirect output > Save the standard output results to the specified file , And overwrite the original file
>> Appends the standard output to the end of the specified file , Don't cover the original content
Standard error output 2> Save the error message to the specified file , And overwrite the original file
2>> Append the error message to the end of the specified file , Don't cover the original content
Mixed output &> and 2>&1 Standard output , The standard error is saved to the same — In file

Case a
Put the standard output result “132456” Save to file passwd.txt; Then enter the standard password to niangao When , From the specified file passwd.txt Read data from :
 Build a

Case 2

>”  It will cover the original file 
“>>”  The original file will not be overwritten 

 Insert picture description here

Case three :& usage

2>/dev/null  ## Output the error to the black hole 
>/dev/null 2>&1  ## Redirect standard output to black hole , Error output 2 Redirect to standard output ( Both standard output and error output go to black hole )
2>&1>/dev/null   ## Error output redirected to standard output , Standard output into black hole 

 Insert picture description here
 Insert picture description here
Add

 Insert picture description here

2.6 Pipeline operation

The pipe symbol “|” The command output on the left , As input to the command on the right ( Deal with people ), Multiple pipes can be used in the same command line

Use format :
cmd1 command 1 | cmd2 command 2[… | cmdn command n]

Pipeline operation
 Insert picture description here

 awk -F:  '{print $1,$3}'   ## It means to force the output of information and print the first and third Columns 

 Insert picture description here

3、 ... and 、Shell Script variables

Various Shell It is used in the environment “ Variable ” The concept of .Shell Variables are used to store specific parameter values that the system and users need to use .

Role of variables
It is used to store specific parameters that the system and users need to use ( value )
Variable name : Use a fixed name , Preset by the system or defined by the user
A variable's value : According to the user settings 、 The system changes with the change of environment


The type of variable

Custom variable : Customized by user 、 Modify and use
Special variables : environment variable , A read-only variable , Positional variable , Predefined variables

environment variable : Maintained by system , Used to set up the work environment
A read-only variable : Used when the variable value cannot be modified
Positional variable : Pass parameters to the script through the command line
Predefined variables :bash A class of variables built into , Cannot be modified directly

3.1 Custom variable

1. Define new variables :

 Format :  Variable name = A variable's value 
[root@pxw ~]# product=c++

2. View the value of the defined variable :

 Format :echo $ Variable name 
[root@pxw ~]# version=3.5.1

 Insert picture description here

3. Special operation of variable assignment

quotes explain
Double quotes Allowed to pass through $ Symbols refer to other variables
Single quotation marks Do not reference other variable values ,$ Treat as normal characters
Apostrophe Command substitution , Extract the output of the command after execution

 Insert picture description here
4.read command

-------- Method 1 :read Command to get input ---------
read [-p " Prompt information "]  Variable name 
echo $ Variable name 
[root@pxw ~]# echo 192.168.61.128 > ip.txt
[root@pxw ~]# read -p "input your IP" < ip.txt
[root@pxw ~]# echo $IP
192.168.100.10

-------- Method 2 : Write... In a script , Implement... On the command line read obtain ---------
read  Variable name 
echo $ Variable name 

Method 1 :
 Insert picture description here

Method 2 :
 Insert picture description here
 Insert picture description here
5. Set the scope of the variable

export  Variable name = Variable 

 Insert picture description here

3.1.1 Operation of numerical variables

Operator :+ Add 、- Subtraction 、* Multiplication 、/ division 、% Remainder

expr  Variable 1  Operator   Variable 2 
var=$(expr  Variable 1  Operator   Variable 2)
var=$(( Variable 1  Operator   Variable 2))
var=$[ Variable 1  Operator   Variable 2]
let var= Variable 1  Operator   Variable 2
 
i++ amount to i=$[$i + 1],i++ Is the assignment first , Re operation 
i-- amount to i=$[$i - 1],++i Is to calculate first and then assign value 
i+=1 amount to i=$[$i + 1]

---- expand -----
[root@Kiro shell]# expr $[2 * 2] ## You can use the normal operator directly in brackets 

Case a : The remainder only needs the remainder after division


# Law 1 
[root@localhost data]#expr 3 % 2 
1
 
# Law two : Defining variables , Use the apostrophe 
[root@Kiro shell]# sum=`expr $X + $X + $Y`
[root@Kiro shell]# echo $sum
301

 Insert picture description here
Case 2 : Extension of multiplication sign
 Insert picture description here
 Insert picture description here

Case three : Script
 Insert picture description here

3.2 environment variable

Environment variable refers to the environment variable generated by Linux A type of variable created by the system in advance , It is mainly used to set the user's working environment , Include user host Directory 、 Command to find the path 、 User current directory 、 Login terminal, etc . The environment variable consists of Linux Automatic system maintenance , It will change with the change of user state :

  • If after modification ,(uname) , Restart to restore the original ;
  • Or copy the previous one and assign the variable directly
 adopt env Command to view , It's all set :
HOSTNAME=Kiro
SHELL=/bin/bash
HISTSIZE=1000
USER=root
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
PWD=/root/shell

 Insert picture description here

Case study :
 Insert picture description here

3.3 Positional variable

In order to use Shell Script program , It is convenient to provide parameters through the command behavior program ,bash The concept of position variable is introduced .

[root@Kiro shell]# cat vars.sh
#!/bin/bash

echo $1
echo $2
echo $3
[root@Kiro shell]# ./vars.sh 11 22 cc
11
22
cc

Case study :
 Insert picture description here

3.4 Predefined variables

And defining variables is bash A special class of pre-defined variables , Can only be used and cannot create new :

$# : Indicates the number of positional parameters in the command line 
$*:  Represents the contents of all unknown parameters 
$?:  Indicates the return status after the execution of the previous command , by 0 The execution is correct , Not 0 Indicates an exception occurred during execution ;
$0:  Indicates the name of the currently executing script or program 
$$:  Indicates the process number of the current script 

Case study :
 Insert picture description here

3.5 Use awk Value extraction IP value

[root@Kiro shell]# ip=`ifconfig ens33|awk /netmask/'{print $2}'`
[root@Kiro shell]# echo $ip
192.168.61.100

3.6 Global and local variables

  • Global variables
 For global variables  export 
[root@Kiro ~]# export Y=22
[root@Kiro ~]# echo $Y
22

 Insert picture description here

  • Local variables
 Local variables are only currently valid 
[root@Kiro ~]# a=100
[root@Kiro ~]# echo $a
100
[root@Kiro ~]# exit
exit
[root@Kiro ~]# echo $a

 Insert picture description here

Can be found in pstree Look at the sub variables in

【 expand 】

  • uname -p ## Query processor model
     Insert picture description here
  • /dev/null ## empty , Error output can be put in
  • Command line input “bc”==Linux The computer

 Insert picture description here
 Insert picture description here

  • permanent /etc/profile

 Insert picture description here

版权声明
本文为[Kiro Jun]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231652526221.html