当前位置:网站首页>Case driven: a detailed guide from getting started to mastering shell programming
Case driven: a detailed guide from getting started to mastering shell programming
2022-06-28 14:56:00 【Hua Weiyun】
@TOC
One 、 summary
Shell It's a command line interpreter , Receive application user commands , To call the kernel of the operating system . It is also a programming language . As a command language , It interprets and executes commands entered by users interactively or automatically interprets and executes a series of preset commands . It is easy to write 、 Very flexible .

Shell Parser
Linux Provided Shell There are several parsers :
cat /etc/shells 
stay centOS The default parser in is bash
echo $SHELL
Two 、 Introductory cases
shell Script to #!/bin/bash start ( Specify the parser )
Case study : Create a Shell Script , Output hello shell
First step : To write shell Script
First create a helloShell.sh Script files , Then type in the following
#!/bin/bashecho "hellom shell"

The second step : function shell Script
- The first one is : use bash or sh+ Relative or absolute path of script ( Don't give script permission )
sh helloShell.sh bash helloShell.shsh /root/Test/helloShell.sh bash /root/Test/helloShell.sh
- The second kind : Execute the script using the absolute or relative path of the input script ( Must have executable permissions )( Without permission, the following error will occur )

First of all, give helloworld.sh The script +x jurisdiction
chmod 777 helloShell.sh And then rerun
./helloShell.sh 
Case study : stay
/root/TestCreate azhangsan.txtThe file of , Then add... To the file“ I love shell”.
The specific implementation is as follows :
[[email protected] Test]# > demo1.sh[[email protected] Test]# vi demo1.sh stay demo1.sh Enter the following in #!/bin/bashcd /root/Testtouch zhangsan.txtecho "I love shell" >>zhangsan.txtTest run successful :


3、 ... and 、Sell The variables in the
System variables
Common system variables $HOME、$PWD、$SHELL、$USER etc.
View the value of the system variable 
Custom variable
Basic grammar
- Defining variables :
Variable = value - Revoke variables :
unset Variable - Declare static variables :
readonly Variable , Be careful : You can't unset
Other instructions
Variable names can be alphabetized 、 Numbers and underscores , But it can't start with a number , Environment variable name is recommended to be capitalized .
No spaces on both sides of equal sign
stay bash in , Variable default type is string type , No direct numerical operation
Value of variable if there is a space , Double or single quotes are required
Case study :
1、 Defining variables S
2、 Revoke variables S
3、 Declare static variables A=2

Add : Promote the variable to the global environment variable , For other purposes Shell Program usage .
grammar :export Variable name
Case study : Use shell Script output variables B


Special variables
$n
$n( Function description :n Is the number ,$0 Represents the script name ,$1-{10})
Case study : Output the script file name 、 Input parameters 1 And input parameters 2 Value
#!/bin/bashecho "$0 $1 $2 "
$#
$# ( Function description : Get the number of all input parameters , Commonly used in cycles )
Case study : Get the number of input parameters
#!/bin/bashecho $#
$*、[email protected]
$*( Function description : This variable represents all the parameters on the command line ,$* Treat all parameters as a whole )
[email protected]( Function description : This variable also represents all the parameters on the command line , however [email protected] Treat each parameter differently )
Case study : Print all parameters entered
#!/bin/bashecho $*echo [email protected]
$?
$? ( Function description : Return status of last executed command . If the value of this variable is 0, Prove that the last command was executed correctly ; If the value of this variable is not 0( Which number is it , It's up to the order itself ), The last command was executed incorrectly .)
Case study : Judge helloShell.sh Whether the script is executed correctly

Four 、 Operators and conditional judgments
Operator
Basic grammar
“$(( Arithmetic expression ))” or “$[ Arithmetic expression ]”- expr + , - , *, /, % .== Be careful :expr Space between operators ==
Case study : Use
expr
1、 Calculation 3+2 Value
expr 2 + 3
2、 Calculation 2+3x4
expr `expr 2 + 3` \* 4
Case study : Use $ Symbol
Calculation 2+3 ride 4
S=$[ (2+3) *4 ]
conditional
Basic grammar
[ condition ]( Be careful condition Space before and after ) If the condition is not empty, it is true,[ lisi ] return true,[] return false.Common judgment conditions
- Compare two integers

Case study : Compare 2 Greater than 1
[ 2 -gt 1 ]
- Judge according to the file authority

Case study :helloShell.sh Whether you have write permission
[ -w helloShell.sh ]
- Judge according to the document type

Case study :
/root/Test/helloShell.shDoes the file in the directory exist
[ -e /root/Test/helloShell.sh ]
5、 ... and 、 Process control
if
Basic grammar
if [ Conditional judgment ];then Program fi if [ Conditional judgment ] then Program fimatters needing attention :
- [ Conditional judgment ], There must be a space between the bracket and the conditional judgment
- if Space after
Case study : Enter a number , If it is 1, The output the number is 1, If it is 2, The output the number is 2, If other , Output nothing .
#!/bin/bashif [ $1 -eq "1" ]then echo "the number is 1"elif [ $1 -eq "2" ]then echo "the number is 2"fi
case
Basic grammar
case $ Variable name in " value 1") If the value of the variable is equal to the value 1, Then execute the procedure 1 ;; " value 2") If the value of the variable is equal to the value 2, Then execute the procedure 2 ;; … Omit other branches … *) If none of the values of the variables are above , Then execute this procedure ;; esacmatters needing attention :
- case Line ending must be a word “in”, Each pattern match must be in right parenthesis “)” end .
- Double a semicolon “;;” Indicates the end of the command sequence , amount to java Medium break.
- final “*)” Represents the default mode , amount to java Medium default.
Case study : Enter a number , If it is 1, The output the number is 1, If it is 2, The output the number is 2, If other , Output other number.
#!/bin/bashcase $1 in "1") echo "the number is 1";;"2") echo "the number is 2";;*) echo "other number";;esac
while
Basic grammar
while [ Conditional judgment ] do Program doneCase study : from 1 Add to 100
#!/bin/bashs=0i=1while [ $i -le 100 ]do s=$[$s+$i] i=$[$i+1]doneecho $s
for
for (( Initial value ; Cycle control conditions ; Variable change )) do Code done for Variable in value 1 value 2 value 3… do Program doneCase study :
1、 Print all input parameters
#!/bin/bashfor i in $*do echo "value is : $i"done 
2、 from 1 Add to 100
#!/bin/bashs=0for((i=0;i<=100;i++))do s=$[$i+$s]doneecho $s
6、 ... and 、 Read console input
Basic grammar
read( Options )( Parameters ) - Options : - `-p: Specify the prompt when reading the value ;` `-t: Specifies the time to wait while reading the value ( second )` Parameters Variable : Specifies the variable name of the read value Case study : Tips 5 Seconds , Read the name entered by the console
#!/bin/bashread -t 5 -p "input your name" NAMEecho $NAME
7、 ... and 、 function
System function
basename Basic grammar
basename [string / pathname] [suffix] Function description :basename The command will delete all prefixes including the last (‘/’) character , Then display the string . Options :suffix For the suffix , If suffix Designated ,basename Will pathname or string Medium suffix Get rid of .Case study : Intercept this
/root/Test/helloShell.shFile name of the path
basename /root/Test/helloShell.sh 
dirname Basic grammar
dirname File absolute path Function description : Remove filename from given filename with absolute path ( Non catalog part ), Then return to the rest of the path ( Part of the catalog )Case study : obtain
helloShell.shPath to file
dirname /root/Test/helloShell.sh 
Custom function
Basic grammar
[ function ] funname[()]{ Action; [return int;]}funnameAdditional explanation :
- Must be before calling function place , Declare function first ,shell The script is run line by line . It doesn't compile first like any other language .
- Function return value , Only through $? System variable acquisition , Can display plus :return return , If not , Results will be run with the last command , As return value .return Heel value n(0-255)
Case study : Calculate the sum of the two input parameters
#!/bin/bashfunction sum(){ s=0 s=$[ $1 + $2 ] echo $s}read -p "input first number: " N1read -p "input second number: " N2sum $N1,$N2;

边栏推荐
- 第四大运营商,难成「鲶鱼」
- 字节跳动埋点数据流建设与治理实践
- 使用LamdbaUpdateWrapper的setSql作用及风险
- 2022 welder (technician) examination question bank simulated examination platform operation
- Ding! Techo day Tencent technology open day arrived as scheduled!
- Does Frankfurt currently support SQL?
- dolphinscheduler2.X的安装(亲测有效)
- Technical trendsetter
- 动力电池,是这样被“瓜分”的
- Steve Jobs of the United States, died; China jobs, sold
猜你喜欢

成龙和快品牌,谁才是快手的救星?

量子前沿英雄谱|“光量子探险家”McMahon:将任何物理系统变成神经网络

Construction and management practice of ByteDance buried point data flow

从小小线虫谈起——溯源神经系统进化,开启生命模拟

Tencent was underweight again by prosus, the major shareholder: the latter also cashed out $3.7 billion from JD

Q-Tester 3.2:适用于开发、生产和售后的诊断测试软件

openGauss内核:SQL解析过程分析

Opengauss kernel: analysis of SQL parsing process

【空间&单细胞组学】第1期:单细胞结合空间转录组研究PDAC肿瘤微环境

QQ被盗号后群发黄图,大批用户“社死”
随机推荐
functools:对callable对象的高位函数和操作(持续更新ing...)
sent2vec教程
Mingchuangyou products passed the listing hearing: seeking dual main listing with an annual revenue of 9.1 billion
Calculator (force buckle)
PMP认证证书的续证费用是多少?
How can I get the stock account opening discount link? Is it safe to open a mobile account?
浪擎与浪潮,一个从OEM到价值共生的生态样板
Seata数据库中出现以下问题要怎么解决啊?
Is PMP really useful?
[MySQL learning notes 23] index optimization
Which is safer, a securities company or a bank? How to open an account is the safest
Opening and closing principle
老板囑咐了三遍:低調、低調、低調
How to solve the following problems in the Seata database?
spacy教程(持续更新ing...)
动力电池,是这样被“瓜分”的
鸟类飞行状态下穿戴式神经信号与行为数据检测记录系统的技术难点总结
Unable to create process using 'd:\program file
【mysql学习笔记24】索引设计原则
Rails进阶——框架理论认知与构建方案建设(一)


