<>shell programming

<> one ,shell How scripts are executed

<>1.1 shell Format requirements for scripts

* Script to #!/bin/bash start
* Script requires executable permissions
<>1.2 Write a shell script

Requirements description : Create a shell script , output hello world~
vi hello.sh
#!/bin/bash
echo “hello world~”

<>1.3 How scripts are executed

Mode 1 ( Enter the relative or absolute path of the script )
explain : First, give hello.sh jurisdiction , Then execute the script

such as /root/sh Use below ./hello.sh

Mode II (sh+ script )
explain : No permission is required for scripts
such as sh hello.sh , It can also be used later

<> two ,shell Variable for

<>2.1shell Introduction to variables

1)Linux shell The variables in are divided into , System variables and user defined variables
2) System variables :$ HOME,$ PWD,$ SHELL,$ USER wait , such as :echo $ HOME
wait
3) Show current shell All variables in :set

<>2.2 Definition of variables

√ Basic grammar
1) Defining variables : Variable name = value

2) Undo variable :unset variable

3) Declare static variables :readonly variable , be careful : No unset

4) Define environment variables ( Define global )
modify /etc/profile file , set up tomcat_home

Reload file
source /etc/profile

#!/bin/bash # case 1: Defining variables A A=100 # Output variables need to be added $echo A=$A echo "A=$A" # case 2: Undo variable A
unset Aecho "A=$A" # case 3: Declare static variables B=2, No unset readonly B=2 echo "B=$B" #unset B
# Assign the result returned by the instruction to the variable C=`date` D=$(date) echo "C=$C" echo "D=$D" # Using environment variables TOMCAT HOME echo
"tomcat home=$TOMCAT HOME"
<>2.3 Position parameter variable

When we execute a shll Script time , If you want to get the parameter information of the command line , You can use position parameter variables
such as :./myshell.sh100 200, This is an execution shell Command line for , Can be found in myshell Parameter information obtained from script

case : Write a shell script position.sh, Get the parameter information of the command line in the script .

<>2.4 Predetermined variable

Basic introduction
namely shell The designer implements the set variables , Can be found in shell Directly execute and use in the script

1)$$( Functional description : Process number of the current process PD))
2) $ ! ( Function description : Process number of the last process running in the background (PD))
3)$?( Function description : Return status of the last executed command . If the value of this variable is 0, Prove that the last command was executed correctly ; If this changes
The value of the quantity is not 0( Which number is it , It is up to the command to decide ), It proves that the last command was executed incorrectly .)

Application examples
shell Scripts simply use predefined variables
#!/bin/bash echo " Currently executing process id=$$" # Run a script in the background , And get his process number /root/shcode/myshell.sh&
echo " Last process running in background mode id=$!" echo " The result of execution is =$?"

<> three ,shell Operator for

Basic introduction
Learn to shell Using operators in

<>3.1 Basic grammar

1) ( ( transport count type ) ) or (( Expression )) or (( Expression )) or [ Expression ] perhaps expr m + n//expression expression
2) be careful expr Space between operators , If you want to expr Assign the result of to a variable , use ``
3)expr m -n
4)expr \ *,/,%
ride , except , Residual

17.8.3 Application examples oper.sh
case 1: calculation (2+3)X4 Value of
case 2: Request two parameters of the command line [ integer ] And 20 50
#!/bin/bash # case 1: calculation (2+3)X4 Value of # Use the first method RES1=$((2+3)*4) echo "res1=SRES1"
# Use the second method , Recommended PES2=$[(2+3)*4] echo "res2=$RES2" # Use the third method expr TEMP=expr 2+3
RES4=expr $TEMP \* 4' echo "temp=STEMP" echo "res4=SRES4"
# case 2: Request two parameters of the command line [ integer ] And 20 50 SUM=$[$1+$2] echo "sum=$SUM"

<> four , Conditional judgment

<>4.1if Conditional judgment statement
[ condition ]( be careful condition Space before and after )
# Non empty return true, Available $? verification (0 by rue,>1 by false)

Application examples
[ hspEdu ] return true
[ ] return false
[ condition ]&& echo OK ‖ echo notok Conditions met , Execute the following statement

Judgement statement
Common judgment conditions
1)= string comparison
2) Comparison of two integers
-t less than
-le Less than or equal to little equal
-q be equal to
gt greater than
ge Greater than or equal to
-ne Not equal to
3) Judge according to file permissions
-r Have read permission
-w Have write permission
-x Have permission to execute
4) Judge by document type
-f File exists and is a regular file
e File exists
-d File exists and is a directory

Application examples
case 1:“ok" Equal to "ok”
Judgement statement : use =
case 2:23 Is it greater than or equal to 22
Judgement statement : use -ge
case 3:root/shcode/aaa.txt Whether the file in the directory exists
Judgement statement : use -f
The code is as follows :
#!/bin/bash # Judge whether it matches u if [ "oks" = "ok" ] then echo " That's a good match " fi # judge 23 Greater than 22 if [
23 -ge 22 ] then echo "23 greater than 22" fi # Determine whether the file exists if [ -f /root/sh/aa.txt ] then echo
" File exists " fi # One more demo test if [ hedhdi ] then echo " True " fi

<>4.2 Multi branch condition judgment

if [ Conditional judgement ]
then
code
elif [ Conditional judgement ]
then
code
fi

matters needing attention :[ Conditional judgement , There must be a space between brackets and conditional expressions ]
Application examples ifCase.sh
case : Please write a sll program , If the input parameter , Greater than or equal to 60, Then output " Passed ", If less than 60, Then output " fail, "
#!/bin/bash if [ $1 -gt 60 ] then echo " Passed " elif [ $1 -lt 60 ] then echo
" fail, " fi

<>4.3case Process control

case sentence
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 the values of variables are not the above values , Then perform this procedure
;;
esac

Application examples testCase.sh
case 1: When the command line parameter is 1 Hour , output " Monday ", yes 2 Hour , Just output " Tuesday ", Output of other conditions "other’"
#!/bin/bash # case 1 The input parameters are 1 Hour , Output Monday , Entered parameter Tuesday hour , The output is Tuesday , In other cases, the output is other case $1 in
"1") echo " Monday " ;; "2") echo " Tuesday " ;; *) echo "other" ;; esac

<>4.4 for Loop statement

Basic grammar 1
for variable in value 1 value 2 value 3…
do
Program code
done
Application examples testForl.sh
case 1: The parameters entered on the print command line can be seen here $ * and $ @ Differences between

Basic grammar 2
for( Initial value ; Cycle control conditions ; Variable change )
do
Program code
done
Application examples testFor2.sh
case 1: from 1 Add to 100 Value output display of
#!/bin/bash # use $* Cyclic output , The value we set for i in "$*" do echo "num is $i" done
# use $@ To get all the parameters , A few parameters will output several lines echo
"===================================================>" for j in "$@" do echo
"num is $j" done

#!/bin/bash # case 1: Calculated 1~100 Sum of SUM=0 for (( i=1; i<=100; i++ )) do # Write your own business code
SUM=$[$SUM+$i] done echo " Sum is sum=$SUM"

<>4.5 while Loop statement

Basic grammar 1
while [ Conditional judgement ]
do
Program code
done
be careful :while and [ There are spaces , Conditional judgement and also have spaces
Application examples testWhile.sh
case 1: Enter a number from the command line n, Statistics from 1++n What is the value of ?
#!/bin/bash #while Statement implementation , Sum of data SUM=0 i=0 while [ $i -le $1 ] do # Execute code
SUM=$[$SUM+$i] # i Autoincrement i=$[$i+1] done echo " The sum is sum=$SUM"

<> five ,read Console input

Basic grammar
read ( option )( parameter )
option :
p: Specify the prompt when reading values ;
: Specify the time to wait while reading the value ( second ), If not entered within the specified time , No more waiting ..
parameter :
variable : Specifies the variable name to read the value from

Application examples testRead.sh
case 1: Read console input one NUM1 value
case 2: Read console input one NUM2 value , stay 10 Seconds input .
#!/bin/bash read -p " Please enter NUM1=" NUM1 echo " input NUM1=$NUM1" #10s Internal waiting input .10s Automatic output if there is no input in
read -t 10 -p " Please enter NUM2=" NUM2 echo " Entered NUM2=$NUM2"

<> six , function

Function introduction

shll Programming is the same as other programming languages , With system function , You can also customize functions . In system function , Let's introduce two here .

<>6.1 System function

basename Basic grammar
function : Return full path last / Part of , Commonly used to get file names
basename [pathname][suffix]
basename [string][suffix]
( Function description :basename The command deletes all prefixes, including the last one (“P) character , Then the string
Show .
option :
suffix Is a suffix , If suffix Assigned ,basename Will pathname or string Medium suffix Remove .
basename /home/aaa/get/aa.text

dirname Basic grammar
function : Return full path last / Front part of , Commonly used in the return path section
dirname File absolute path ( Function description : Removes a file name from a given file name that contains an absolute path ( Non catalog parts ), Then return to the rest of the path ( Part of the catalog ))
dirname /home/aaa/get/aa.text

<>6.2 Custom function

Basic grammar
[ function ] funname[()]
{
Action;
[return int;]
}
Call direct write function name :funname [ value ]

Application examples
case 1: Calculate the sum of the two input parameters ( Dynamic acquisition ),getSum
code
#!/bin/bash # Define function function getSum(){ SUM=$[$n1+$n2] echo " the sum sum=$SUM" } # Enter two values
read -p " Please enter the first value n1=" n1 read -p " Please enter the second value n2=" n2 # Call function getSum $n1 $n2

<> seven ,shell Programming comprehensive case ( Data backup )

requirement analysis
l) Every morning 2:30 Backup database hspedu reach /data/backup/db
2) The start and end of backup can give corresponding prompt information
3) The file name of the backed up file should be the backup time , And packaged into .tar.gz Form of , such as :2021-03-12_230201.tar.g
4) While backing up , Check for 10 Database files backed up days ago , Delete if any .
5) Draw a thought analysis diagram

code
#!/bin/bash # Backup directory BACKUP=/data/backup/db # current time DATATIME=$(date
+%Y-%m-%d_%H%M%S) echo $DATATIME # Address of the database HOST=localhost # Users of the database DB_USER=root
# Password for the database DB_PASSWORD=root # Backup database name DATABASE=chat # Create backup directory , Create if does not exist [ ! -d
"${BACKUP}/${DATATIME}" ] && mkdir -p "${BACKUP}/${DATATIME}" # Database backup mysqldump
-u${DB_USER} -p${DB_PASSWORD} --host=${HOST} -q -R --database ${DATABASE} |
gzip > ${BACKUP}/${DATATIME}/${DATATIME}.sql.gz # Package files into tar.gz file cd ${BACKUP}
tar -zcvf $DATATIME.tar.gz ${DATATIME} # Delete the corresponding backup file rm -rf ${BACKUP}/${DATATIME}
# delete 10 Backup files days ago find ${BACKUP} -atime +10 -name "*.tar.gz" -exec rm -rf {} \; echo
" Backup database ${DATABASE} success "
Set the program in the early morning of each day 2:30 Automatic execution ;
Set scheduled task
[root@VM-20-10-centos ~]# crontab -e
View scheduled tasks
[root@VM-20-10-centos ~]# crontab -l 30 2 * * * /usr/sbin/mysql_db_backup.sh

Technology
©2019-2020 Toolsou All rights reserved,
evo Tool usage problems ——Degenerate covariance rank, Umeyama alignment is not possible Experiment 4 Automated test tools - software test mysql Export data sql sentence _mysql according to sql Query statement export data Create a thread ——— Javaweb (3) Data structure experiment ( three )—— Stacks and queues TS stay vue2 Writing in the project web Front end signature plug-in _signature_pad Plug in implements electronic signature function docker Where is the image stored Qt Getting Started tutorial 【 Basic controls 】QCalendarWidget calendar control springboot How to get reality in ip address