当前位置:网站首页>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;

边栏推荐
- Q-tester 3.2: applicable to development, production and after-sales diagnostic test software
- Ding! Techo day Tencent technology open day arrived as scheduled!
- dolphinscheduler2.X的安装(亲测有效)
- How does Seata server 1.5.0 support mysql8.0?
- 【mysql学习笔记23】索引优化
- 运行近20年,基于Win 98的火星探测器软件迎来首次升级
- 开闭原则
- Calculator (force buckle)
- Which securities company is the largest and safest? How to open an account is the safest
- How to solve the following problems in the Seata database?
猜你喜欢

Le patron a donné trois ordres: discret, discret, discret
![[C language] how to generate normal or Gaussian random numbers](/img/31/964e0922e698a3746599b840501cdf.png)
[C language] how to generate normal or Gaussian random numbers

The hidden crisis of Weilai: past, present and future

Recommended practice sharing of Zhilian recruitment based on Nebula graph

字节跳动埋点数据流建设与治理实践

第四大运营商,难成「鲶鱼」

vscode编写markdown文件并生成pdf

After nearly 20 years of operation, the Mars probe software based on win 98 has been upgraded for the first time

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

The time schedule for the soft test in the second half of 2022 has been determined!
随机推荐
Q-tester 3.2: applicable to development, production and after-sales diagnostic test software
智能化转型被加速,企业需要新的工具箱
Ding! Techo day Tencent technology open day arrived as scheduled!
[spatial & single cellomics] phase 1: Study on PDAC tumor microenvironment by single cell binding spatial transcriptome
Send2vec tutorial
10 key points to effectively improve performance interview
请问一下,是不是insert all这种oracle的批量新增没拦截?
Dry goods | how to calculate the KPI of scientific researchers, and what are the h index and G index
Tencent was underweight again by prosus, the major shareholder: the latter also cashed out $3.7 billion from JD
代码片段
法兰克福地区目前支持sql了吗?
Calculator (force buckle)
Gas station (greedy)
腾讯再遭大股东Prosus减持:后者还从京东套现37亿美元
新零售线下店逆势起飞,通膨乌云下的消费热情
Steve Jobs of the United States, died; China jobs, sold
flutter 系列之:flutter 中的 offstage
快手投资电商服务商易心优选
抽奖动画 - 鲤鱼跳龙门
Which is safer, a securities company or a bank? How to open an account is the safest


