当前位置:网站首页>Shell programming specifications and variables
Shell programming specifications and variables
2022-07-29 03:02:00 【Pupils with a bad stomach】
One 、Shell Script Overview
Shell The concept of script
- 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
Shell Script application scenarios
- · Repetitive operations
- Interactive tasks
- Batch transactions
- Service running status monitoring
- Scheduled task execution
- ......
Shell The role of
shell The role of —— command interpreter ,“ The interpreter ”
- Between the system kernel and the user , Responsible for interpreting the command line

Two 、 Write the first Shell Script
Write script code
- Use vim Text editor
- One in each line Linux command , Write in order
#vim first.sh
cd /boot/
pwd
ls -lh vml*Give executable permission
- Make the script executable
# chmod +x first.sh

Shell Script execution
- Method 1 : Command to specify the path , It is required that the document must have x jurisdiction .
chmod +x lroot/ first.sh
Specify the absolute path :/root/first.sh
Specify the relative path :./ first.sh
- 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
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 auxl wc -l
echo "abc123" l passwd --stdin zhangsan
3、 ... and 、 Redirect
1、 Interactive hardware devices
- The standard input : Slave device ( Character device : Keyboard and mouse ) Receiving data from users
- standard output : Through the equipment ( Monitor ) Output data to users
- The standard error : Through the equipment ( Monitor ) Report execution error message
| 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 |
2、 Redirection operation
| type | The operator | purpose |
| Redirect input | < | Read data from the specified file |
| Redirect output | > | Save the standard output results to the specified file , And cover the original content |
| >> | Appends the standard output result 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 cover the original content |
| 2>> | Append the error message 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 |
Four 、shell Script variables
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
Custom variable : Defined by the user , Modify and use
environment variable : Maintained by system , Used to set up the work environment
A read-only variable : Can only be read and cannot be changed
Positional variable : Pass parameters to the script through the command line
Predefined variables :Bash A class of variables built into , Do not modify
3. Custom variable
Format : Variable name = A variable's value
- Variable name : A place where data is temporarily stored
- A variable's value : Temporary town change data
- There is no space on either side of the equal sign . Variable names should start with letters or underscores , Do not include special characters in the name ( Such as +、-、*、/、.、?、%、&、# etc. )
Use echo View and reference the values of variables
By adding a leading symbol before the variable name "$", You can reference the value of a variable , Use echo Command can view variables , Can be in one echo View multiple variable values at the same time in the command
echo $ Variable name # Look at the value of the variable ,$ Replace the representative symbol for the variable
unset A variable's value # Cancel variables
echo Options :
echo -n Indicates no line feed output
Use echo -e Output escape characters , Output the escaped content to the screen
The commonly used 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


4. Define variables interactively (read command )
You can also use Bash Built-in commands read To assign a value to a variable . Used to prompt the user to enter information , So as to realize a simple interactive process . It will be executed from the standard input device ( keyboard )7 Read in a line , And use a space as a separator , Assign the read fields to the specified variable in turn ( The extra content is assigned to the last variable ). If only one variable is specified , Assign the entire line to this variable .

Define variables interactively (read)
- -p Information to prompt users
- -n Define the number of characters
- -s Don't show user input , Commonly used to enter passwords read -s -p "input your password:" pass
- -t Define timeout , If you haven't lost for more than a long time, you will automatically quit


stty echo // Turn on screen echo Operation content : Add (+)、 reduce (-)、 ride (*)、 except (/、 Remainder (%)
Operation symbol :$(o) and $[]
Operation command :expr and let
Computing tools :bc( System comes with )
expr command ( It can not only calculate , It also supports output to the screen )
Several commonly used operators are as follows .
- +: Addition operation .
- -: Subtraction .
- \*: Multiplication , Be careful not to use only "*" Symbol , Otherwise, it will be treated as a file wildcard .
- /: Division operations .
- %: Modular operation , Also known as remainder operation , Used to calculate the remainder after the division of numerical values .


Use bc Carry out operations , Support decimal operations , However, it cannot be used directly in the script, otherwise it will enter the interactive interface , It can be used echo Use in combination with piping


Boolean value : really (true) Or false (false)

Common operational expressions :
- i=s (expr 12 \*5)
- i=$((12* 5))
- i=[12 * 5]
- let i=12*5
- i++ amount to i=$[$i+1]
- i-- amount to i=$[$i-1]
- i+=2 amount to i=$[$i+2]
echo $RANDOM Random generation 0-32767 The random number

5. 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 , You can't assign values to predefined variables directly . Predefined variables use "$" A combination of a symbol and another symbol indicates
- $#: Indicates the number of positional parameters in the command line J
- $*: Represents the contents of all positional parameters , These contents as a whole
- [email protected]: Indicates that all position parameters are listed , But it is listed in a single form
- $?: Indicates the return status after the execution of the previous command , The return value is О The execution is correct , Return any non О Values indicate an exception in execution .
- $0: Indicates the name of the currently executing script or program
- $$: Indicates that the process number of the current process is returned
- $!: Returns the process number of the last background process
$* Print out a whole


[email protected] Print out individual


边栏推荐
- MYSQL入门与进阶(十四)
- navicat新建数据库
- Analysis of Project-based Learning Creativity in steam Education
- Verilog的时间系统任务----$time、$stime、$realtime
- .NET 序列化枚举为字符串
- Interpretation of ue4.25 slate source code
- JVM基础入门篇一(内存结构)
- (job) C language: Simulation Implementation of ATOI and strncpy, strncat, strncmp
- 10. Writing rules - Document Search
- MYSQL入门与进阶(十三)
猜你喜欢

Jinshan cloud returns to Hong Kong for listing: Hong Kong stock rush of Chinese to B cloud manufacturers

C language: Little Lele and hexadecimal conversion

Analysis of Project-based Learning Creativity in steam Education

HTB-Blue

(job) C language: Simulation Implementation of ATOI and strncpy, strncat, strncmp

Notes on the sixth day

单例模式(饿汉式 懒汉式)

盘点国内外项目协同管理软件:SaaS和定制化成趋势

SQL查询数据之多表(关联)查询

sqlilabs less-32~less-33
随机推荐
常用hooks总结
MYSQL入门与进阶(十四)
MySQL large table joint query optimization, large transaction optimization, avoiding transaction timeout, lock wait timeout and lock table
Zone --- line segment tree lazy marking board sub problem
Day 5 experiment
C陷阱与缺陷 第3章 语义“陷阱” 3.7 求值顺序
DataGrip 如何导出和恢复整个数据库数据,使用单个 SQL 文件
融云实时社区解决方案
seed 随机种子
vim常用命令
Confusion matrix learning notes
Shell编程规范与变量
C#从网址异步获得json格式的数据
HTB-Blue
瀚高数据库最佳实践配置工具HG_BP日志采集内容
盘点国内外项目协同管理软件:SaaS和定制化成趋势
混淆矩阵学习笔记
Linux下安装MySQL8.0的详细步骤
解析机器人与人类情感共鸣的主观意识
MySQL - the difference between count (field), count (primary key), count (1), count (*)