当前位置:网站首页>Shell script learning notes
Shell script learning notes
2022-06-27 11:50:00 【Zhaoyanjun】
Reprint please indicate the source :http://blog.csdn.net/zhaoyanjun6/article/details/122923763
This article from the 【 Zhao Yanjun's blog 】
List of articles
What is? Shell
Shell It's a use. C A program written in a language , It is used by users Linux The bridge .Shell It's a command language , Another programming language .
Shell Script
Shell Script (shell script), It's for shell Write the script .
Shell Environmental Science
Shell Programming with JavaScript、php Programming is the same , Just have a text editor that can write code and a script interpreter that can interpret execution .
Shell grammar
Open the text editor ( have access to vi/vim Command to create a file ), Create a new file test.sh, extension sh(sh representative shell), The extension does not affect script execution , It's good to see the name and know the meaning , If you use php Write shell Script , Use the extension php Okay .
Grant Execution Authority
chmod +x ./test.sh # Give the script permission to execute
./test.sh # Execute the script
Log output echo
echo "Hello World !"
Variable
When defining variables , There can be no spaces between variable names and equal signs , This may not be the same as any programming language you are familiar with . meanwhile , The naming of variable names should follow the following rules :
- Only English letters can be used for naming , Numbers and underscores , The first character cannot begin with a number .
- No spaces in between , You can use underscores _.
- You can't use punctuation .
- Out of commission bash Keywords in ( You can use help Command to view reserved keywords ).
Example :
your_name="runoob.com"
Variable references
your_name="qinjx"
echo $your_name
echo ${
your_name}
Curly braces outside variable names are optional , Add it or not , Curly braces are used to help the interpreter identify the boundaries of variables , For example, the following situation :
your_name="qinjx"
echo $your_name
echo ${
your_name}hello
A read-only variable
Use readonly Commands can define variables as read-only variables , The value of a read-only variable cannot be changed .
The following example attempts to change a read-only variable , The result is wrong :
myUrl="https://www.google.com"
readonly myUrl
myUrl="https://www.runoob.com"
Run script , give the result as follows :
/bin/sh: NAME: This variable is read only.
character string
Strings can be in single quotes , You can also use double quotes , You can also use no quotes .
- Any character in a single quotation mark will be output as is , Variables in a single quoted string are invalid ;
- A single quotation mark cannot appear in a single quotation mark string ( You can't escape a single quotation mark ), But in pairs , Use as string concatenation .
The advantages of double quotes :
- You can have variables in double quotes
- Escape characters can appear in double quotes
if else
if Sentence syntax format :
if condition
then
command1
command2
...
commandN
fi
give an example :
a=10
b=10
if [ $a == $b ]
then
echo "a be equal to b"
elif [ $a -gt $b ]; then
echo "a Greater than b"
elif [ $a -lt $b ]; then
echo "a Less than b"
else
echo " There are no conditions that meet "
fi
for loop
for The general format of the loop is :
for var in item1 item2 ... itemN
do
command1
command2
...
commandN
done
Write in a line :
for var in item1 item2 ... itemN; do command1; command2… done;
give an example :
for i in {
1..5} ; do
echo " Traverse $i"
done
Output :
Traverse 1
Traverse 2
Traverse 3
Traverse 4
Traverse 5
give an example :
for str in Hello new world
do
echo " Traverse $str"
done
Output :
Traverse Hello
Traverse new
Traverse world
while sentence
while Loop is used to execute a series of commands continuously , Also used to read data from the input file . Its grammatical form is :
while condition
do
command
done
give an example :
int=1
while(( $int<=5 ))
do
echo $int
let "int++"
done
Run script , Output :
1
2
3
4
5
The above example uses Bash let command , It is used to execute one or more expressions , There is no need to add $ To represent a variable .
give an example :
num=18
while [ $num -le 100 ] #-le Less than or equal to
do
let num++
echo "while $num"
done
case … esac
case … esac Select multiple statements for , And in other languages switch … case Statements like , It's a multi branch selection structure , Every case The branch begins with a right parenthesis , Use two semicolons ;; Express break, The end of execution , Jump out of the whole case … esac sentence ,esac( Namely case In turn, ) As the closing tag .
case … esac The syntax is as follows :
case value in
Pattern 1)
command1
command2
...
commandN
;;
Pattern 2)
command1
command2
...
commandN
;;
esac
case Work as shown above , Value must be followed by word in, The first mock exam must be closed with right brackets. . Value can be variable or constant , Match found that after the first mock exam meets a certain pattern, , During this period, all commands are executed until ;;.
Value will detect every matching pattern . Once the patterns match , After the corresponding command of matching mode is executed, other modes will not be continued . If there is no matching pattern , Use the asterisk * Capture the value , Then execute the following command .
give an example :
echo ' Input 1 To 4 Number between :'
echo ' The number you enter is :'
read aNum
case $aNum in
1) echo ' You chose 1'
;;
2) echo ' You chose 2'
;;
3) echo ' You chose 3'
;;
4) echo ' You chose 4'
;;
*) echo ' You didn't enter 1 To 4 Number between '
;;
esac
string matching
site="runoob"
case "$site" in
"runoob") echo " Novice tutorial "
;;
"google") echo "Google Search for "
;;
"taobao") echo " TaoBao "
;;
esac
The output is :
Novice tutorial
Array
Example 1:
name=(zhao zhang li)
echo " Elements :${name[1]}"
echo " All the elements :${name[*]}"
echo " The length of the array :${#name[*]}"
echo " The length of the array :${#name[@]}"
Example 2:
# Copy to an element individually
name[1]=wang
function
shell The definition format of the function in is as follows :
[ function ] funname [()]
{
action;
[return int;]
}
explain :
- 1、 You can take function fun() Definition , It can also be direct fun() Definition , Without any parameters .
- 2、 Parameter return , Can display plus :return return , If not , Results will be run with the last command , As return value . return Heel value n(0-255)
give an example
demoFun(){
echo " This is my first shell function !"
}
echo "----- The function starts executing -----"
demoFun
echo "----- The function is finished -----"
Output results :
----- The function starts executing -----
This is my first shell function !
----- The function is finished -----
Here's a definition with return Function of statement :
function sum() {
a=10
b=20
return $((a+b))
}
echo ' Start function '
sum
# Receive function return value
echo "result: $?"
Output results :
Start function
result: 30
The return value of the function passes through $? To obtain a .
Be careful : All functions must be defined before use . This means that you have to put the function at the beginning of the script , until shell When the interpreter first discovered it , Can be used . Call a function using only its function name .
Function arguments
stay Shell in , You can pass parameters to a function when you call it . Inside the body of the function , adopt $n To get the value of the parameter , for example ,$1 Represents the first parameter ,$2 Represents the second parameter …
Examples of functions with arguments :
function sum() {
# $1 Represents the first parameter ,$2 Represents the second parameter .
a=$1
b=$2
return $((a+b))
}
echo ' Start function '
sum 2 3
# Receive function return value
echo "result: $?"
Output :
Start function
result: 5
give an example :
funWithParam(){
echo " The first parameter is zero $1 !"
echo " The second parameter is $2 !"
echo " The tenth parameter is $10 !"
echo " The tenth parameter is ${10} !"
echo " The eleventh parameter is ${11} !"
echo " The total number of parameters is $# individual !"
echo " Output all parameters as a string $* !"
}
funWithParam 1 2 3 4 5 6 7 8 9 34 73
Output results :
The first parameter is zero 1 !
The second parameter is 2 !
The tenth parameter is 10 !
The tenth parameter is 34 !
The eleventh parameter is 73 !
The total number of parameters is 11 individual !
Output all parameters as a string 1 2 3 4 5 6 7 8 9 34 73 !
Be careful , 10 No can a take The first Ten individual ginseng Count , a take The first Ten individual ginseng Count Need to be want 10 Can't get the tenth parameter , Getting the tenth parameter requires 10 No can a take The first Ten individual ginseng Count , a take The first Ten individual ginseng Count Need to be want {10}. When n>=10 when , Need to use ${n} To get the parameters .
in addition , There are also a few special characters for processing parameters :
- $* : Display all the parameters passed to the script in a single string
- @ : And @ : And @: And * identical , But use quotation marks , And return each parameter in quotation marks .
External file references
Like any other language ,Shell You can also include external scripts . This can easily encapsulate some common code as a separate file .
Shell The file contains the following syntax format :
. filename # Note the number (.) There is a space between the file name and the file name
or
source filename
This method , Many tool classes can be encapsulated
First, define a tool class util.sh:
url="baidu.com"
function sum() {
# $1 Represents the first parameter ,$2 Represents the second parameter .
echo " All the parameters :$* "
a=$1
b=$2
return $((a+b))
}
test.sh
# External file references
. util.sh
echo " Variable references :$url"
echo ' Start function '
#sum Function in util.sh in
sum 2 3
# Receive function return value
echo "result: $?"
Determines if the string is empty
str="abc"
if [ -z $str ]; then
echo " The string is empty "
else
echo " String is not empty "
fi
test command
Shell Medium test The command is used to check if a condition holds , It can do numerical 、 Character and file testing .
- The numerical test
-eq : Equal is true
-ne : True if not equal
-gt : Greater than is true
-ge : True if greater than or equal to
-lt : Less than is true
-le : True if less than or equal to
give an example :
num1=100
num2=100
if test $[num1] -eq $[num2]
then
echo ' Two numbers are equal !'
else
echo ' The two numbers are not equal !'
fi
Output results :
Two numbers are equal !
- Basic operation
In code [] Perform basic arithmetic operations , Such as :
a=5
b=6
result=$[a+b] # Note that there should be no spaces on either side of the equal sign
echo "result by : $result"
The result is :
result by : 11
- String test
= Equal is true
!= Inequality is true
-z character string A zero length string is true
-n character string True if the length of the string is not zero
example
num1="ru1noob"
num2="runoob"
if test $num1 = $num2
then
echo ' Two strings are equal !'
else
echo ' Two strings are not equal !'
fi
Output results :
Two strings are not equal !
- File test

give an example :
if test -e ./bash
then
echo ' file already exist !'
else
echo ' file does not exist !'
fi
Output results :
file already exist !
in addition ,Shell It also provides ( -a )、 or ( -o )、 Not ( ! ) Three logical operators are used to connect test conditions , Its priority is : ! The highest , -a second , -o The minimum . for example :
if test -e ./notFile -o -e ./bash
then
echo ' At least one file exists !'
else
echo ' Neither file exists '
fi
Output results :
At least one file exists !
http curl
curl The command uses... By default get Mode sending http request .
curl www.baidu.com
Practice one : Traversal folder
# Define Directory , Traverse the current directory
fileDir="./*"
# Traverse the directory
for file in $fileDir ; do
echo " Traverse :$file"
done
Output :
Traverse :./main
Traverse :./test
Traverse :./test.sh
Traverse :./util.sh
Output files in directory 、 Folder
# Define Directory
fileDir="./*"
# Traverse the directory
for file in $fileDir; do
if test -f "$file"; then
echo " Traverse :$file It's a document "
elif test -d "$file"; then
echo " Traverse :$file Is a directory "
fi
done
Actual combat II : Deep traversal of folders
# Folder Directory
fileDir="../assets"
function allFile() {
# Receiving parameters
dir=$1
# Traverse the directory
for file in ${dir}/*; do
if test -f "$file"; then
echo "$file It's a document "
elif test -d "$file"; then
echo "$file Is a directory "
allFile "$file"
fi
done
}
echo " Start traversing the directory "
allFile $fileDir
Output results :

边栏推荐
- Jerry's DAC output mode setting [chapter]
- R language uses the poisgof function of epidisplay package to test the goodness of fit of Poisson regression and whether there is overdispersion
- [tcapulusdb knowledge base] Introduction to tcapulusdb system management
- R语言使用epiDisplay包的dotplot函数通过点图的形式可视化不同区间数据点的频率、使用by参数指定分组参数可视化不同分组的点图分布、使用dot.col参数指定分组数据点的颜色
- 优博讯出席OpenHarmony技术日,全新打造下一代安全支付终端
- C语言0长度数组的妙用
- 杰理之睡眠以后定时唤醒系统继续跑不复位【篇】
- R语言fpc包的dbscan函数对数据进行密度聚类分析、plot函数可视化聚类图
- Excel中输入整数却总是显示小数,如何调整?
- 千万不要错过,新媒体运营15个宝藏公众号分享
猜你喜欢

15+ urban road element segmentation application, this segmentation model is enough!
![[tcapulusdb knowledge base] Introduction to tmonitor system upgrade](/img/04/b1194ca3340b23a4fb2091d1b2a44d.png)
[tcapulusdb knowledge base] Introduction to tmonitor system upgrade
![Jerry's serial port communication serial port receiving IO needs to set digital function [chapter]](/img/d1/5beed6c86c4fdc024c6c9c66fbffb8.png)
Jerry's serial port communication serial port receiving IO needs to set digital function [chapter]

杰理之串口通信 串口接收IO需要设置数字功能【篇】

【TcaplusDB知识库】TcaplusDB单据受理-建表审批介绍

QStyle实现自绘界面项目实战(一)

Nvme2.0 protocol - new features
![Jerry's DAC output mode setting [chapter]](/img/2e/62bc74e216ed941bd2a0a191db63f0.png)
Jerry's DAC output mode setting [chapter]

AutoCAD - three pruning methods

Code for structural design of proe/creo household appliances - electric frying pan
随机推荐
Unity shader learning (II) the first shader
JSP custom tag
alibaba jarslink
21: Chapter 3: develop pass service: 4: further improve [send SMS, interface]; (in [send SMS, interface], call Alibaba cloud SMS service and redis service; a design idea: basecontroller;)
Oracle group statistics query
Jerry's serial port communication serial port receiving IO needs to set digital function [chapter]
The R language uses the follow up The plot function visualizes the longitudinal follow-up map of multiple ID (case) monitoring indicators, and uses stress The labels parameter adds label information t
【TcaplusDB知识库】TcaplusDB系统管理介绍
Drive to APasS!使用明道云管理F1赛事
[tcapulusdb knowledge base] tcapulusdb doc acceptance - create business introduction
[tcapulusdb knowledge base] Introduction to tcapulusdb table data caching
【TcaplusDB知识库】TcaplusDB常规单据介绍
千万不要错过,新媒体运营15个宝藏公众号分享
Unity Shader学习(二)第一个Shader
Deep understanding of happens before principle
建木持续集成平台v2.5.0发布
2022CISCN华中 Web
Naacl 2022 | TAMT: search the transportable Bert subnet through downstream task independent mask training
R语言glm函数构建二分类logistic回归模型(family参数为binomial)、使用AIC函数比较两个模型的AIC值的差异(简单模型和复杂模型)
Unity Shader学习(一)认识unity shader基本结构