当前位置:网站首页>[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
边栏推荐
- The Missing Semester
- C summary of knowledge points 3
- Machine learning - Data Science Library - day two
- JPA and criteria API - select only specific columns - JPA & criteria API - select only specific columns
- uniapp 使用 uni-upgrade-center
- Redis startup and library entry
- Emotion analysis based on IMDB comment data set
- I'm in Zhongshan. Where is a better place to open an account? Is it actually safe to open an account online?
- 用于分类任务的数据集划分脚本
- Is it safe for Huatai Securities to open an account online?
猜你喜欢

The Missing Semester

Technology sharing | MySQL: how about copying half a transaction from the database?

Uniapp uses uni upgrade Center

Summary of JFrame knowledge points 1

Typora adds watermarks to automatically uploaded pictures

MQ prevent message loss and repeated consumption

用实际例子详细探究OpenCV的轮廓检测函数findContours(),彻底搞清每个参数、每种模式的真正作用与含义

强大、好用、适合程序员/软件开发者的专业编辑器/笔记软件综合评测和全面推荐

基于IMDB评论数据集的情感分析

Typora realizes automatic uploading of picture pasting
随机推荐
On recursion and Fibonacci sequence
241. Design priority for operational expressions: DFS application questions
ACLY与代谢性疾病
Use set_ Handler filters out specific SystemC wrapping & error messages
华为HMS Core携手超图为三维GIS注入新动能
【datawhale202206】pyTorch推荐系统:召回模型 DSSM&YoutubeDNN
[Yunju entrepreneurial foundation notes] Chapter VII Entrepreneurial Resource test 1
Technology sharing | MySQL: how about copying half a transaction from the database?
二叉堆(一) - 原理与C实现
Rural guys earn from more than 2000 a month to hundreds of thousands a year. Most brick movers can walk my way ǃ
Typora realizes automatic uploading of picture pasting
MQ prevent message loss and repeated consumption
Computer graduation project asp Net attendance management system vs developing SQLSERVER database web structure c programming computer web page source code project
栈的应用——括号匹配问题
Mechanism and type of CPU context switch
[Yunju entrepreneurial foundation notes] Chapter 7 Entrepreneurial Resource test 2
Impressive bug summary (continuously updated)
Huawei HMS core joins hands with hypergraph to inject new momentum into 3D GIS
Uniapp uses uni upgrade Center
Virtualenv+pipenv virtual environment management