当前位置:网站首页>[shell programming] - shell introductory learning
[shell programming] - shell introductory learning
2022-07-01 12:08:00 【Pacifica_】
Shell Introduction learning
summary
Shell What is it?
Shell It's a command line interpreter , It provides a way for users to Linux The kernel sends requests to run the program's interface system level program , Users can use Shell To start up , Hang up , stop it , Write some programs
Linux It needs to be written in operation and maintenance Shell Program to manage the server ; To write Shell Scripts can be used for program or server maintenance , Such as the script of regularly backing up the database
introduction
To write Shell Script
Create and save a .sh file (Shell Scripts are usually written in sh Suffixed name , But it's not necessary )
Script files must be in #!/bin/bash start
There is no need to add a semicolon at the end of each statement in the script file
'#' For single line comments ; use ":<<!“ as well as ”!" Include content for multi line comments , And these two symbols should occupy a separate line :
:<<!
The comment
!
hello world Example :
#!/bin/bash
echo "hello world"
perform Shell Script
The way 1: Enter the absolute or relative path of the script . First, give the script file executable permission
The way 2:sh Script file path , The script can be executed directly without giving executable permission . This is not recommended
Variable
Shell The variables in are divided into system variables and user-defined variables
System variables such as $HOME,$PWD,$SHELL,$USER,$PATH wait , Such as echo "PATH=$PATH"
Use set Command to view the current Shell All variables in
Defining variables : Variable = value
Revoke variables :unset Variable
A=100
echo "A=$A" # Output A=100. use '$' To reference variables , Or add braces :${ Variable name }
unset A
echo "A=$A" # Output A=
Declare static variables :readonly Variable ( Static variables cannot unset, There's... In the script unset An error will be reported when executing the script for the operation of static variables )
Rules for variable definition
1. Variable names can be made up of letters , Numbers , Underline composition , But don't start with a number ( Will report a mistake )
2. No spaces on both sides of equal sign
3. Variable names are usually capitalized
Assign the return value of the command to the variable
1.A=`ls - la`, The quotation marks , Run the command inside , And return the result to the variable A
2.A=$(ls - la), Equivalent to backquotes ;MYDATE=$(date), Get the date and assign a value
environment variable
In profile ( Such as /etc/profile file ) Set environment variables in , It can be quoted elsewhere export Variable name = A variable's value , take shell Variable output is environment variable source The configuration file , Let the modified configuration information take effect immediately $ Variable name , Take the value of the environment variable
Position parameter variable
When executing a shell Script time , If you want to get the parameter information of the command line , You can use the position parameter variable . Such as execution ./myshell.sh 10 20 On command , Want to be in myshell.sh Get from the script file 10 or 20 These parameters in the command line
The specific method of use is in shell The following symbols are used in the script :$n,n Is the number ,$0 The command itself ,$1-$9 Represents the first to ninth parameters , Parameters above ten need to be enclosed in braces , Such as ${13}$*, Represents all parameters in the command line , Treat all parameters as a whole [email protected], It also represents all parameters in the command line , But it treats each parameter differently $#, Represents the number of all parameters in the command line
Predefined variables
The predefined variable is shell Variables that have been defined by the designer in advance , Can be directly in shell Use in script $$, The process number of the current process (PID)$!, The process number of the last process running in the background (PID)$?, Return status of last executed command . If its value is zero 0, It indicates that the last command was executed correctly ; If it is not right 0( The specific number depends on the command itself ), It means that the last command was executed incorrectly
Operator
Grammatical form :$(( Arithmetic expression )) or $[ Arithmetic expression ]( recommend )
`expr m + n`,expr There should be spaces between operators in ; Enclose in back quotation marks , And there must be no space between the backquote and the preceding equal sign
`expr m - n`
`expr \*` Multiplication ,`expr /` division ,`expr %` Remainder
Multiplication ’*' The backslash before is used to escape ,expr If there are left and right parentheses in, you also need to escape
conditional
[ condition ], Be careful condition Space before and after
Not empty return true, You can use $? verification ,0 by true,>1 by false;[] return false
Conditional judgment symbol
The following symbols should have spaces on the left and right
A comparison of two integers
-lt Less than ;-le Less than or equal to ;-eq be equal to ;-gt Greater than ;-ge Greater than or equal to ;-ne It's not equal to = String comparison . The comparison result can be used ! Take the opposite
Judge according to the file authority
-r Have read permission ;-w Have the right to write ;-x Have the authority to execute
Put the file to be judged to the right of the symbol
Judge according to the document type
-f The file exists and is a regular file -e File exists -d The file exists and is a directory
Put the file to be judged to the right of the symbol
Process control
if sentence
if [ Conditional judgment ];then
Other statements
fi
perhaps
if [ Conditional judgment ]
then
Other statements
elif [ Conditional judgment ]
then
Other statements
fi
There must be a space between the bracket and the conditional judgment in the conditional judgment ; Recommend the second way
case sentence
case $ Variable name in
" value 1")
# If the variable value is a value 1, Execute the statement here
;;
" value 2")
# If the variable value is a value 2, Execute the statement here
;;
......
*)
# If the value of the variable is not the value listed above , Execute the statement here
;;
esac
for sentence
for Variable in value 1 value 2 value 3...
do
Other statements
done
perhaps
for(( Initial value ; Cycle control conditions ; Variable change ))
do
Other statements
done
Example 1: Print parameters in the command line
Script files test.sh:
#!/bin/bash
for i in "$*"
do
echo "num is $i"
done
perform ./test.sh 10 20 30 After the command , The console will print out num is 10 20 30. because $* Treat the command line parameters as a whole . use [email protected] Instead of $* Words , Will be output :
num is 10
num is 20
num is 30
This is it. $* and [email protected] The difference between
Example 2: from 1 Add up to 100 Output results
SUM=0
for((i=1;i<=100;i++))
do
SUM=$[$SUM+$i]
done
echo "SUM=$SUM"
while sentence
while [ Conditional judgment ]
do
Other statements
done
Example : Enter a number... From the command line n, Statistics from 1 Add to n Value
#!/bin/bash
SUM=0
i=0
while [ $i -le $1 ] # You can judge whether spaces are needed according to color changes , If it's here while If the space behind is removed while It changes color , Instructions need spaces
do
SUM=$[$SUM+$i]
i=$[$i+1]
done
echo "sum= $SUM"
read Read console input
read [ Options ] [ Parameters ]
Options :-p, Specify the prompt when reading the value ;-t, Specifies the time to wait while reading the value ( second ), If it is not entered in the specified time , I don't wait
Parameters : Specifies the variable name of the read value
function
shell The functions in have system functions , You can also have custom functions
Examples of system functions
basename
This function is used to return the last of the full path / Part of , Often used to get file names
basename [path] [suffix]
basename [string] [suffix]
Options suffix For the suffix , If suffix Designated ,basename Will path or string Medium suffix Get rid of , Such as basename /home/test/test.txt .txt You'll get test
dirname
This function returns the full path last / The front part of , Commonly used in the return path part
dirname File absolute path
Such as dirname /home/test/test.txt You'll get /home/test
Custom function
[ function ] funName[()]
{
Action;
[return int;]
}
Write the function name directly when calling funName. Brackets here function as well as return A sentence means you can leave it unwritten
Example : Calculate the sum of the two input parameters
#!/bin/bash
function getSum(){
SUM=$[$n1+$n2]
echo " And for $SUM"
}
read -p " Please enter the first number " n1
read -p " Please enter the second number " n2
getSum $n1 $n2
You can see that there are no formal parameters
边栏推荐
- 指纹浏览器工作原理、使用场景以及重要性简单讲解
- Sum of factor numbers of interval product -- prefix sum idea + fixed one shift two
- GID:旷视提出全方位的检测模型知识蒸馏 | CVPR 2021
- Emotion analysis based on IMDB comment data set
- Computer graduation project asp Net hotel room management system VS development SQLSERVER database web structure c programming computer web page source code project
- C serialization simple experiment
- 自定义 grpc 插件
- Huawei HMS core joins hands with hypergraph to inject new momentum into 3D GIS
- Golang introduces the implementation method of the corresponding configuration file according to the parameters
- Leetcode (Sword finger offer) - 58 - ii Rotate string left
猜你喜欢

On recursion and Fibonacci sequence

Theoretical basis of graph

Powerful, easy-to-use, professional editor / notebook software suitable for programmers / software developers, comprehensive evaluation and comprehensive recommendation

谈思生物直播—GENOVIS张洪妍抗体特异性酶切技术助力抗体药物结构表征

【datawhale202206】pyTorch推荐系统:召回模型 DSSM&YoutubeDNN

91. (cesium chapter) cesium rocket launch simulation

Botu V15 add GSD file

How to understand the developed query statements

Onenet Internet of things platform - create mqtts products and devices

技术分享 | MySQL:从库复制半个事务会怎么样?
随机推荐
自定义 grpc 插件
Typora adds watermarks to automatically uploaded pictures
【单片机】【数码管】数码管显示
Exposure: a white box photo post processing framework reading notes
The Missing Semester
leetcode 406. Queue Reconstruction by Height(按身高重建队列)
The specified service is marked for deletion
Onenet Internet of things platform - mqtt product equipment upload data points
Botu V15 add GSD file
Talk about the pessimistic strategy that triggers full GC?
About keil compiler, "file has been changed outside the editor, reload?" Solutions for
Redis configuration environment variables
Value/sortedset in redis
研发效能度量框架解读
[Yunju entrepreneurial foundation notes] Chapter 7 Entrepreneurial Resource test 8
谈思生物直播—GENOVIS张洪妍抗体特异性酶切技术助力抗体药物结构表征
Dlhsoft Kanban, Kanban component of WPF
Mysql database knowledge collation
构建外部模块(Building External Modules)
[Yunju entrepreneurial foundation notes] Chapter 7 Entrepreneurial Resource test 2