当前位置:网站首页>Shell programming specifications and variables
Shell programming specifications and variables
2022-07-28 15:44:00 【Ruthless】
Catalog
4、shell What can we do ( Preliminary understanding )
1、Shell The composition of the script
3、 ... and 、 Redirection and pipeline operation
Four 、shell Action type of variable
2.2、echo Output variable value
2.3、 Single quotation marks 、 Double quotes 、 Apostrophe
2.4、 Define variables interactively (read)*
2.5、 Action range of variable ( Local and global variables )
5、 ... and 、 Variable operation
One 、Shell
1、shell Introduction to
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 the operation instructions input by the user ( command ) And explain , Pass the operation to be performed to the kernel for execution , And output the execution result .
Bash(/bin/bash) It's most at the moment Linux The default version is Shell.
2.shell species
common shell There are many interpreters , Use different shell, Its internal instructions 、 There are some differences in command prompt and so on , adopt /etc/shells The file can understand what the current system supports shell Types of scripts .
shell The type of shell The function of
/bin/sh yes shell Command soft link ( Has been /bin/bash Replaced by )
/bin/bash Base on FNU Developed under the framework of shell
/usr/bin/sh Has been /bin/bash Replace
/usr/bin/bash centos and redhat By default, the system uses bash
/bin/tcsh csh Enhanced Edition , And csh Fully compatible with , Integrated csh, More features
/usr/sbin/nologin Make users unable to log in to the host
/sbin/nologin Soft connection
3、shell What is a script ?
shell The script is to put the original linux Put the command or statement in a file , And then through this program file to execute , Let's call this program shell Or scripts .
Save the commands you need to execute to a file , Execute in order , It doesn't need to compile , It's interpretive .
4、shell What can we do ( Preliminary understanding )
Automate the installation and deployment of software
Complete the management of the system automatically , Such as adding users in batch
Automate backup , Such as regular database backup
Automated analytical processing , Such as website visits
Application scenarios *
Repetitive operations 、 Interactive tasks 、 Batch transactions 、 Service running status monitoring 、 Scheduled task execution 、......
Two 、shell Script
1、Shell The composition of the script
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 


2、Shell Script execution
1、 Path execution
Command to specify the path , It is required that the document must have x jurisdiction .
chmod +x /opt/xg.sh
Specify the absolute path :/opt/xg.sh
Specify the relative path :./xg.sh( Script environment )

Exit script environment


2、sh or bash perform
Appoint Shell To explain the script , It is not required that the document must have x jurisdiction .
sh Script path :sh -x xg.sh perhaps bash -x xg.sh

3、source perform
source Script path ( System environment ) Do not require the file to have Execution Authority :. xg.sh perhaps source xg.sh


3、 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 .
ps aux | wc -l
echo "abc123" | passwd --stdin zhangsan
3、 ... and 、 Redirection and pipeline operation
Interactive hardware devices
| 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 | The operator | purpose |
| Redirect input | < | Read data from the specified file |
| Redirect output | > | Put the standard output result preservation To the specified file , And cover the original content |
| >> | Put the standard output result Additional To the end of the specified file , Don't cover the original content | |
| Standard error output | 2> | Put the error message preservation To the specified file , And cover the original content |
| 2>> | Put the error message Additional To the end of the specified file , Don't cover the original content | |
| Mixed output | &> | Standard output 、 Standard errors are saved to the same file |
| 2>&1 | Redirect standard error output to standard output |
1、 Redirect input
Redirecting input refers to changing the way of receiving input in the command from the default keyboard to Specified file , Instead of waiting for input from the keyboard .
Redirect input using “ < ” The operator , By redirecting input, some interactive operations can be completed by reading files .
explain : Redirect input is used , You can input the contents of a file to other places you want to receive , There is no need to enter manually .
echo "123456" > pass.txt
useradd zhangsan
passwd --stdin zhangsan < pass.txt
combination cat Use


Configure with script yum Warehouse

2、 Redirect output
Redirecting output refers to saving the normal output of a command to a specified file , Instead of directly on the screen of the monitor .
Redirect output using “ > ” or “ >> ” Operation symbol , Used to overwrite or append files, respectively .
If the target file for redirection output does not exist , The file will be created , Then save the output result of the previous command to the file , If the target file already exists , The output result is overwritten or appended to the file 
And cat Use a combination of

3、 Standard error output
Error redirection refers to the error message that will appear during the execution of the command ( For example, the parameter of the option is wrong ) Save to the specified file , Instead of being displayed directly on the screen , Error redirection using “ 2> ” The operator .
effect
in application , Error redirection can be used to collect error information about program execution , Provide basis for troubleshooting .
You can also redirect unimportant error messages to an empty file /dev/null in , To keep the output of the script concise

4、 Mixed output
① Correct and error information are saved in the same file

② Redirect standard error output to standard output

Four 、shell Action type of variable
1、 Action type of variable
environment variable : Maintained by system , Used to set up the work environment
Positional variable : Pass parameters to the script through the command line
Custom variable : Defined by the user 、 Modify and use
Predefined variables :Bash A class of variables built into , Cannot be modified directly
Role of variables : It is used to store specific parameters that the system and users need to use ( Or 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、 Custom variable
2.1、 Definition of variables
Format : Variable name = A variable's value ( Be careful = There should be no spaces on either side )
Undefine variables :unset Variable name
Variable names need to start with letters or underscores , The name should not contain special characters ( Such as :+、-、*、/、.、?、%、&、# etc. )
By adding a leading symbol before the variable name “ $” , You can reference the value of a variable , Use echo Command to view variables , You can also view multiple variable values at the same time .


2.2、echo Output variable value
When the variable name is easily confused with other characters immediately following it , You need to add braces “ {} ”, Enclose it , Otherwise, the correct variable cannot be determined , For undefined variables , Will be displayed as a null value .

①echo Common options
-n : Indicates no line feed output
-e : Output escape characters , Output the escaped content to the screen

② Escape characters are as follows :
\c: Don't wrap output stay “\c” If there are no characters after , The effect is equivalent to echo -n
\n: Line break
\t: After escape, it means to insert tab, That's the tab ( Multiple spaces )
③ Escape character \

2.3、 Single quotation marks 、 Double quotes 、 Apostrophe
① Double quotes (“”): Allowed to pass through $ The symbol references other variable values
Double quotation marks are mainly used to define strings , Especially when the content to be assigned contains spaces , Must be enclosed in double quotation marks , In other cases, it is usually possible to omit

② Single quotation marks (‘’): Do not reference other variable values ,$ Treat as normal characters
When the content to be assigned contains $、“ 、\ And other characters with special meaning , Should be enclosed in single quotation marks .
Within single quotation marks , You will not be able to reference the values of other variables , Any character is treated as a normal character , Display what you enter ,
But when the assignment content contains single quotation marks , Need to use \ Symbols are transferred , To avoid conflict .

③ Apostrophe (``): Command substitution , Extract the output of the command after execution ,`…` and $(…) The same effect


!! Be careful : The apostrophe above can be used to assign an executable command line to a variable , However, nested substitution operations cannot be formed in one line of command , At this time, you can use “ $() ” Instead of the apostrophe , To solve the problem of nesting .

2.4、 Define variables interactively (read)*
You can define a variable , Change this variable to the value entered by the user
①read Common options
| Options | function |
|---|---|
| -p | Information to prompt users |
| -n | Define the number of characters |
| -s | Don't show user input , Commonly used to enter passwords |
| -t | Define timeout , If you haven't lost for more than how long, you will automatically quit |


2.5、 Action range of variable ( Local and global variables )
By default , The newly defined variable is only in the current shell Effective in the environment , So it's a local variable , When entering subroutine or subroutine shell Environmental time , Local variables will no longer be used .

In order to make User defined variables in all children shell Can continue to be used in the environment , Reduce repeated settings , It can be done by internal command export Set the variables as global variables everywhere , You can specify multiple variable names as parameters at the same time ( No need to use " $ " Symbol ), Multiple variable names are separated by spaces
Format 1:export Variable name
Format 2:export Variable name = A variable's value


env View the user's current environment variables

3、 Special variables
3.1、 environment variable
Environment variables refer to those that are required by Linux A type of variable created by the system in advance , It is mainly used to set the user's working environment , It will change with the change of user state .
Use env The environment variables in the current working environment can be found by the command , For some common environment variables, we should understand their respective purposes 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 ;
PATH: Indicates command search path, etc ;
RANDOM: Represents a random number , Returns the 0-32767 The integer of
Variable PATH Represents the default search path for executable programs
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

PATH Variable
Used to set the executable default search path , When only the file name is specified to execute the command program ,Linux The system will be in PATH Variable to find the corresponding executable file . That is to say, if there is an executive document , Want to execute this file directly , Then the path of this file needs to be in $PATH Inside , If not , Want to execute , You must add a path to execute .
① Put the script directory in $PATH Inside as follows :
② Put your script into $PATH In a directory in
The global configuration file of the environment variable is /etc/profile, The variables defined in this file apply to all users . Each user also has its own independent configuration file (~/.bash_profile). It can be used to change or set an environment variable for a long time .
vim /root/.bash_profile
export HISTSIZE=200 # modify root The number of historical command records of the user
3.2、 A read-only variable
shell There is a special case in variables , Once set , Its value is unchangeable , This variable is called a read-only variable .
You can set it as a read-only property when creating , You can also set an existing variable as a read-only property , Read only variables are mainly used for variable values that cannot be modified , Cannot be deleted .
readonly Command to set read-only variables
product=benet
readonly product # Set to read-only variable
echo $product
product=accp # Read only variables cannot be reassigned
unset product # Read only variables cannot be deleted ,unset The command is used to delete variables
3.3、 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 taking one to the ninth parameter , More than ten parameters need to be represented by braces , For example, the tenth parameter is ${10}

3.4、 Predefined variables
The predefined variables are created by Bash A class of special variables pre-defined by a program , Users can only use predefined variables , You cannot create a new predefined variable , Nor can you directly predefine variable assignment , Predefined variables use “ $ ” A combination of a symbol and another symbol indicates .
Predefined variables function
$# Indicates the number of positional parameters in the command line
$* Represents the contents of all locations , These contents as a whole
[email protected] Indicates that all position parameters are listed , But it is listed in a single form
$? Table the return status after the execution of the previous command , 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 .
$0 Indicates the name of the currently executing script or program
$$ Indicates that the current process number is returned
$! Returns the process number of the last background process


understand “ $ ” and “ [email protected] ” The difference between *
$*: Think of all parameters as a whole string separated by spaces ( Single string ), 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 returned as a string , representative “$1" “$2” “$3"”$4"

5、 ... and 、 Variable operation
Operation content : Add (+)、 reduce (-)、 ride (*)、 except (/)、 Remainder (%)
Operation symbol : $(()) and $[]
Operation command : expr and let
Computing tools : bc( System comes with )
1、expr command
The operation of integer value is mainly through internal command expr Conduct , Between operators and variables , There must be at least one space , It can not only perform operations , It also supports output to the screen
Format :expr Variable 1 Operator Variable 2 [ Operator Variable 3]
Operator :+ Add 、- Subtraction 、\* Multiplication 、/ division 、% Remainder



2、 Operation symbol
$(()) and $ [] And echo Together with , Because it can only calculate and cannot output results , Between these two operation symbols , No need to use $ Symbols refer to variables , You can use expressions directly
2.1 $(()) Use of symbols

2.2、 $[] Use of symbols

2.3、let command
let The operation of can change the value of the variable itself , But don't show the results , need echo.

i++ amount to i=$[$i+1]
i-- amount to i=$[$i-1]
i+=2 amount to i=$[$i+2]
i++ Operation after assignment
++i Evaluate first and then assign
2.4、 bc command
Use bc Carry out operations , Support decimal operations , But it cannot be used directly in scripts , Otherwise, you will enter the interactive interface , have access to echo Use in combination with piping .
Support decimal operations , But it cannot be used directly in scripts , Otherwise, you enter the interactive interface , So in use , Need to add echo expression + Pipe, + bc . You can also use scale The command indicates how many decimal places to keep , direct scale=2, Means to keep two decimal places . Add to the expression , That is to say : echo ”scale=2; expression “ | bc


bc Make logical judgment

2.5 Variable format
① Format : Variable name = A variable's value
“=” Indicates assignment
Variable naming rule : Start with a letter or underline , Case sensitive
product=benet
version=6.0
name="zhang san
② Look at the value of the variable
Format :echo $ Variable name
name=lisi
wang=45+
echo $name
echo ${wang} ${name} View multiple variables
echo $wang1
echo ${wang}1 Braces define a variable as an integer

summary
shell The role of : Mainly for automatic operation
1、shell The programming specification of
Be careful shell The order of , To use .sh ending , The parser needs to be injected into the script , The default parser is :#!/bin/bash,shell There are many ways to implement , You can use absolute or relative paths to execute scripts , But this method needs to add execution permission , If you don't add execution permission , have access to bash、sh、source Order to execute
2、 Redirection and pipeline operation
Redirect
With standard input (stdin)、 standard output (stout)、 Error output (stderr)
" > ": Indicates standard redirection output , Can combine cat Enter some information manually , End of input , Will overwrite the previous content
“ >> ”: Indicates redirection output , Redirect the manually entered content to the file
“ < ” : Indicates redirection input , combination cat When using , You can input the contents of the file into cat in , then cat Output content
“ << ” : Indicates that it ends with a set character , Most of them use EOF
“1>&2” : Indicates that the standard output will be , Mixed into the error output
“2>&1” : Indicates that the error will be output , Mixed into standard output
Pipe symbol “ | ”
Indicates the execution result before the pipe symbol , Output to the pipeline symbol for execution
3、shell Variable
① Custom variable
have access to echo Add parameters to output . Sometimes variable output should be output together with ordinary content , have access to ${} Reference the variable name to distinguish .
The function of single quotation mark ( ‘ ’ ) : The contents of quotation marks are the contents to be output , Does not transform the inside of quotation marks
The function of double quotation marks (“ ”): Indicates the contents of quotation marks for output , But the internal variables will be output ,echo The default is double quotation marks , Usual echo When there are spaces in the output , It can be marked with double quotation marks .
The function of single apostrophe (``): Indicates the contents of the apostrophe , Must be an executable command , But this cannot be nested , So you can use $() Input nested output , Output from the inside out .
Define variables interactively : Use read Variables can be obtained from the user's hand , Interact with users , add -p You can enter interactive prompt information ,-t, When the user enters the variable content , Don't show
** Action range of variable : ** Variable action range , In the current shell Environment , If you use bash Turn on a dime shell, Then its parent process shell Variables of will not be available , You can use commands export Add local variables to global variables ,
② Special variables
environment variable : The name of the variable automatically generated for the system , Different variable names represent different meanings , And change with the user state , among $ PATH Indicates the variable path that the command can generate , When we execute a command , He would search for $PATH Command below
A read-only variable : Variables can only be read and cannot be modified or deleted , have access to readonly Add the variable name to generate
Positional variable : Use $1 ,$2 ,$3… And so on represent the position variable ,$0 Represents the script name , The location variable needs to be input by the user when executing the script .
Predefined variables : $#: Represents the number of location variables , ∗ : surface in position Set up change The amount Of Inside Rong , discharge stay One rise transport Out , *: Represents the content of the location variable , Put them together and output ,∗: Represents the content of the location variable , Put them together and output ,@: Represents the content of the location variable , Show output separately ,$?: Indicates whether the last command was executed correctly ,$0: Represents the script name
4、 Variable operation
expr command : It can not only perform operations , You can also display and output , It should be noted that , A space is required on both sides of the operator , Otherwise, an error will be reported .
Use expr command , Basically ,+、-、*、/、%、 operation
Operation symbol operation : $[] perhaps $ (( )) The contents of these two brackets can be calculated , But it can only perform operations , Cannot output results , So we need to combine echo For the output . And there is no need to use $ Symbols to declare variables , Variable values can be used directly .
let command : let The command can change the value itself , It is equivalent to calculating the variable itself , Then assign it to itself ,
But no output , It also needs the help of echo For the output ,
bc command : Support decimal operations , But it cannot be used directly in scripts , Otherwise, you enter the interactive interface , So in use , Need to add echo expression + Pipe, + bc . You can also use scale The command indicates how many decimal places to keep , direct scale=2, Means to keep two decimal places . Add to the expression , That is to say : echo ”scale=2; expression “ | bc
边栏推荐
- Give you a linked list, delete the penultimate node of the linked list, and return the head node of the linked list.
- Youdao cloud notes remove the bottom advertisement
- Camera连拍自动化测试shell脚本
- NFTScan 与 NFTPlay 在 NFT 数据领域达成战略合作
- 全国985院校考研信息汇总整理
- Rxdart is used instead of stateful in fluent
- Voice social system -- improve the audio system industry chain
- Canoe tutorial
- 给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
- Vs dynamic library debugging
猜你喜欢

Editor in ArcGIS Pro

Baidu proposes a dynamic self distillation method to realize dense paragraph retrieval by combining interactive model and double tower model

DNS域名解析协议

程序员的自我修养

Heap operation

详解.NET的求复杂类型集合的差集、交集、并集

MIT pointed out that the public pre training model should not be used indiscriminately

软件架构与设计(六)-----层次结构体

vs动态库调试

爆肝整理 JVM 十大模块知识点总结,不信你还不懂
随机推荐
How to obtain and embed go binary execution package information
3、基本常数和宏定义
Share the HR experience of the first and second tier companies
Monkey stress test
4. Main program and cumulative interrupt processing routine implementation code
Baidu proposes a dynamic self distillation method to realize dense paragraph retrieval by combining interactive model and double tower model
10. Implementation of related data accumulation task
Five connection modes of QT signal and slot
根据输入target,返回数组的两个下标。
shell编程规范与变量
Regular expression (4)
Tencent interview -- please design a thread pool to implement sequential execution
迟来的2021年终总结
Huawei has a record number of employees worldwide: 194000, with research and development personnel accounting for nearly 50%
软件架构与设计(五)-----以数据为中心的架构
Vs usage skills
生命的感悟
软件架构与设计(九)-----基于组件的架构
软件架构与设计(四)-----数据流架构
软件架构与设计(六)-----层次结构体


