当前位置:网站首页>Basic editing specifications and variables of shell script
Basic editing specifications and variables of shell script
2022-07-04 01:41:00 【Official certification】
One 、Shell
●Linux A special program running in a system
1、Shell The role of
●shell: Between the system kernel and the user , Responsible for interpreting the command line
2、 User login Shell
● The user login Linux System time , Automatically load a Shell Program
●bash yes Linux It is used by default in the system Shell Program
●bash The file is located in /bin/bash

Two 、Shell Script Overview
1、 Save the commands to be executed in order to a text file
2、 Give the file executable permissions
3、 It can combine all kinds of Shell Control statements to perform more complex operations
1、Shell Script application scenarios
Repetitive operations
Interactive tasks
Batch transactions
Service running status monitoring
Scheduled task execution
……
3、 ... and 、 To write Shell Script
1、 Write script code
1、 Use vim Text editor
2、 One in each line Linux command , Write... In order of execution

2、 Execute script file ( Three ways )
① Method 1 : Script file path ( Absolute path and relative path , need x jurisdiction )

Relative paths :

Absolute path


② Method 2 :sh Script file path ( Don't x jurisdiction )
Relative paths

Absolute path

③ Method 3 :source or . Script file path ( Unwanted x jurisdiction )
source Commands are also called “ Click command ”, It's a dot symbol (.), yes bash The internal order of
Unwanted x jurisdiction , You also need to use relative or absolute paths

3、 Better script composition
● Script declaration
● Annotation information
● Executable statement
1. Script statement ( Interpreter ): If the first act “#!/bin/bash”, This line of code is represented by /bin/bash Program to explain the execution of ,#!/bin/bash Is the default interpreter . There are other types of interpreters , such as #!/usr/bin/python、#!/usr/bin/expect.
2. Annotation information : With “#” The opening statement is expressed as a comment message , The commented statement will not be executed while the script is running .
3. Executable statement : such as echo command , For output " " String between
Writing process :

Execution results :

Four 、 Redirection and pipeline operation
1、 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

2、 Redirection operation

example :
setenforce 0
useradd zhangsan
echo “123123” > 1.txt
passwd --stdin zhangsan < 1.txt

example :
cat 1.txt
echo “123123” >> 1.txt
cat 1.txt

example :
ls -lh > log.txt 2>&1 Equate to ls -lh &> log.txt
>( Save the standard output results to the specified file )
2>&1( Redirect standard error output to standard output )
&>( Standard output 、 Standard error output is saved to the same file )
2、 Pipe symbol operation “|”
● Output the command on the left , As input to the command on the right ( Deal with people ), Multiple pipes can be used in the same command line .
example :ps aux | wc -l Show all processes

example : Pipe symbols match xargs usage

xargs Commands can accept strings through pipes , And the received string is divided into many parameters by space ( By default, it is separated by spaces ) Then pass the parameter to the following command , As the command line parameter of the following command
5、 ... and 、Shell Role of variables 、 type
Variables are values that change , What doesn't change is constants
1、 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
2、 The type of variable
● Custom variable : Defined by the user 、 Modify and use
● Special variables : environment variable 、 A read-only variable 、 Positional variable 、 Predefined variables
6、 ... and 、 Custom variable
Define a new variable
Variable name = A variable's value # Variable names start with letters or underscores , Case sensitive , It is suggested to use all capitals
echo $ Variable name # Look at the value of the variable
- 1.
- 2.
- 3.

Equal sign (=) Used to assign values to variables
Equal sign (=) To the left of the operator is a variable name , Equal sign (=) To the right of the operator is the value stored in the variable
1、 Use quotation marks when assigning values
Double quotes : Allowed to pass through $ The symbol references other variable values
Single quotation marks : Do not reference other variable values , $ Treat as normal characters
Apostrophe : Command substitution , Extract the output of the command after execution ,`` and $(…) The same effect


2、 Assign values to variables from keyboard input
read Command to get input
Method 1 :
read -p Prompt information Variable name
echo $ Variable name
- 1.
- 2.

Method 2 :
Write... In a script , Implement... On the command line read obtain
vim name.sh
#!/bin/bash
read -p “ Please enter your name ” NAME
echo "--------"
read -p “ Please enter his name ” NAME2
echo "--------"
echo " Your name is "
echo $NAME
echo " His name is "
echo $NAME2
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.

Execution results :

3、 Set the scope of the variable
have access to pstree Command view Shell Environmental Science , Input bash The command enters the sub Shell Environmental Science ,
Press Ctrl+D Key combination or enter exit Command exit Shell Environmental Science

Use bash The command enters the sub Shell Environmental Science

By default , The newly defined variable is only in the current Shell Effective in the environment , So it's called a local variable . When entering a subroutine or a new subroutine Shell Environmental time , Local variables will no longer be used .
It can be done by internal command export Exports the specified variable as a global variable , Enables user-defined variables in all child variables Shell Can continue to be used in the environment .
Format 1:export Variable name
Format 2:export Variable name = A variable's value
- 1.
- 2.


4、 The operation of integer variables
Operator :+ Add 、- Subtraction 、* Multiplication 、/ division 、% Remainder
Common operational expressions :
i=$(expr 12 \* 5)
i=$((10 * 5))
i=$[10 * 4]
let i=10*3
i++ amount to i=$[$i+1]
i-- amount to i=$[$i-1]
i+=2 amount to i=$[$i+2]
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.

7、 ... and 、 special Shell Variable
1、 environment variable
Created in advance by the system , Used to set up the user's work environment
The configuration file :/etc/profile( Global effect )、~/.bash_profile( Current user environment )
2、 Common environment variables
PWD、PATH
USER、SHELL、HOME
Use env The command can view the environment variables in the current working environment
Variable USER Represents the user name ,HOME Represents the user's Host Directory ,LANG Represents the language and character set ,PWD Indicates the current working directory , Variable PATH Represents the default search path for executable programs
①、PATH( Path environment variable )
echo $PATH # View the current search path
PATH="$PATH:/root" # take /root Add directory to search path
export PATH="$PATH:/root" # The output is a global environment variable
first.sh
- 1.
- 2.
- 3.
- 4.



The directory has been added to the path environment variable , All files with execution permission in the directory , Can be executed in any directory in the current environment
②、 A read-only variable
Used when the variable value cannot be modified
readonly Command to set read-only variables
readonly PRODUCT # Set to read-only variable
echo $PRODUCT
PRODUCT=Python # Read only variables cannot be reassigned
unset PRODUCT # Read only variables cannot be deleted ,unset The command is used to delete variables , But you cannot delete read-only variables , It can only be solved by restarting the system
- 1.
- 2.
- 3.
- 4.
- 5.

③、 Positional variable
When performing command line operations , The first field represents the command name or script program name , The remaining string parameters are assigned to the position variable in order from left to right .
$n:n Is the number ,$0 For the order itself ,1~9 Represents the first to ninth parameters , More than ten parameters need to be represented by braces , For example, the tenth parameter is ${10}
vim lic.sh
#!/bin/bash
echo $1
echo $2
echo $1 + $2
- 1.
- 2.
- 3.
- 4.
- 5.
④、 Predefined variables
$*、[email protected]: Represents the parameters to be processed by a command or script .
$*: Think of all parameters as a whole string separated by spaces , representative "$1 $2 $3 $4".
[email protected]: Separate each parameter with double quotation marks into n A list of the parameters of the , Each parameter is independent Of , representative "$1" "$2" "$3" "$4".
$0: Represents the name of the currently executing script or command .
$#: Represents the number of parameters to be processed by a command or script .
$?: Indicates the return status code after the execution of the previous command or script , The return value is 0 The execution is correct , Return any non 0 Values indicate an exception in execution .
It is also often used for Shell Script return Exit function and return the exit value .
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
vim mybak.sh
#!/bin/bash
time=backup-`date +%F`.tar.gz
tar zcf $time $* &> /dev/null #/dev/null Represents a black hole file , Usually used to discard unwanted data output
echo " Has been carried out $0 Script ,"
echo " To complete $# Backup of objects "
echo " Specific contents include : $*"
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
chmod +x mybak.sh
./mybak.sh /etc/passwd /etc/shadow
- 1.
- 2.





summary
shell The role and application scenarios of
shell Script writing specification and execution method
The role and usage of redirection and pipeline
Single quotation marks when assigning custom variables 、 Double quotes 、 How to use the apostrophe
Common operators for numeric variables :+、-、\*、/、%
environment variable 、 A read-only variable 、 Positional variable 、 Purpose of predefined variables
边栏推荐
- Gnupg website
- Notice on Soliciting Opinions on the draft of information security technology mobile Internet application (APP) life cycle security management guide
- Trading software programming
- Openbionics robot project introduction | bciduino community finishing
- How to use AHAS to ensure the stability of Web services?
- 长文综述:大脑中的熵、自由能、对称性和动力学
- Development of user-defined navigation bar in uniapp
- Fundamentals of machine learning: feature selection with lasso
- Lightweight Pyramid Networks for Image Deraining
- 2022 R2 mobile pressure vessel filling certificate examination and R2 mobile pressure vessel filling simulation examination questions
猜你喜欢

Pyinstaller packaging py script warning:lib not found and other related issues

Huawei BFD and NQA

Huawei cloud micro certification Huawei cloud computing service practice has been stable

Audio resource settings for U3D resource management

Force buckle day32

【.NET+MQTT】. Net6 environment to achieve mqtt communication, as well as bilateral message subscription and publishing code demonstration of server and client

Long article review: entropy, free energy, symmetry and dynamics in the brain

Feign implements dynamic URL

长文综述:大脑中的熵、自由能、对称性和动力学

Openbionics exoskeleton project introduction | bciduino community finishing
随机推荐
Lightweight Pyramid Networks for Image Deraining
Introduction to superresolution
CLP information - how does the digital transformation of credit business change from star to finger?
Conditional statements of shell programming
Fundamentals of machine learning: feature selection with lasso
Use classname to modify style properties
C import Xls data method summary V (complete code)
TP5 automatic registration hook mechanism hook extension, with a complete case
C library function int fprintf (file *stream, const char *format,...) Send formatted output to stream
Pesticide synergist - current market situation and future development trend
How to delete MySQL components using xshell7?
技術實踐|線上故障分析及解决方法(上)
What is the student party's Bluetooth headset recommendation? Student party easy to use Bluetooth headset recommended
Huawei cloud micro certification Huawei cloud computing service practice has been stable
2022 new examination questions for safety management personnel of hazardous chemical business units and certificate examination for safety management personnel of hazardous chemical business units
Decompile and modify the non source exe or DLL with dnspy
Difference between value and placeholder
0 basic learning C language - nixie tube dynamic scanning display
Day05 branch and loop (II)
7.1 learning content
