Linux study notes two shell script programming

Shell script programming

Script format requirements

1. The script starts with #!/bin/bash
2. The script needs to have executable permissions

The first shell script

vim hello.sh
#!/bin/bash
echo "hello,world~"

Common execution methods of scripts

1. (Enter the absolute path or relative path of the
script ) First give the script +x permission, and then execute
Insert picture description here

Insert picture description here
Insert picture description here
2. Sh+ script, no need to give script+x permission, just execute it directly
Insert picture description here

Shell variables

1. The variables in the Linux Shell are divided into system variables and user-defined variables.
2. System variables: $HOME $PWD $SHELL $USERetc.
3. Display all variables in the current shell: set
4.${ }中放的是变量,例如echo ${PATH}取PATH变量的值并打印,也可以不加括号比如$PATH

Definition of shell variables

Basic syntax
1. Define variable: variable name=value
2. Unset variable: unset variable
3. Declare static variable: readonly variable, cannot be unset

application

vim var.sh
#!bin/bash
#定义变量A
A=100
#输出变量,需要加上$
echo $A
echo A=$A
echo "A=$A"
#撤销变量A
unset A
echo "A=$A"
#声明静态变量B
readonly B=2
echo "B=$B"

Rules for outputting
Insert picture description here
shell variables

1. Variable names can consist of letters, numbers and underscores, but they cannot start with numbers.
2. There can be no spaces on both sides of the equal sign.
3. Variable names are generally capitalized.

Assign the return value of the command to a variable

1、

A=`date`

Run the command inside and return the result to variable A

2. A= is $(date)equivalent to using backticks

For example, add the following statement in the above example

#将指令返回的结果赋给变量
C=`date`
D=$(date)
echo "C=$C"
echo "D=$D"

The output result has
Insert picture description here
set environment variables

Basic syntax
1. Export variable name = variable value: output shell variables as environment variables
2. Source configuration file: make the modified configuration information take effect immediately
3. Echo variable name: query the value of environment variables

After the environment variable is set, it can be used in the shell program

Multi-line comments for shell scripts

:<<!
内容
!

Positional parameter variable

When we execute a shell script, if we want to get the parameter information of the command line, we can use positional parameter variables, such as: ./myshell.sh 100 200, this is a command line to execute the shell, which can be in the myshell script Get parameter information

Basic syntax
$n: n is a number, $0 represents the command itself, $1-$9 represents the first to ninth parameters, parameters above ten, parameters above ten need to be enclosed in braces, such as ${10}

$*: represents all the parameters in the command line, and treats all the parameters as a whole

$@: also represents all the parameters in the command line, but treats each parameter differently

$#: Represents the number of all parameters in the command line

For example: write script myshell.sh

vim myshell.sh
#!/bin/bash
echo "0=$0 1=$1 2=$2"
echo "所有的参数=$*"
echo "所有的参数=$@"
echo "参数的个数=$#"

Enter the command and get the
Insert picture description here
predefined variables

The variables defined by the shell designer in advance can be used directly in the shell script

Basic syntax
$$: the process number of the current process

$!: The process number of the last process running in the background

$?: The return status of the last executed command. If the value of this variable is 0, it proves that the previous command was executed correctly. If the value of this variable is not 0, it proves that the previous command was executed incorrectly.

For example, write preVar.sh script

#!/bin/bash
echo "当前执行的进程id=$$"
#以后台的方式运行一个脚本,并获取它的进程号
/root/shcode/myshell.sh &
echo "最后一个后台方式运行的进程id=$!"
echo "执行的结果是=$?"

The execution result is
Insert picture description here

Arithmetic operation

Basic syntax
1, $((运算式))or $[运算式]
2, expr m + nif you want to assign the result of expr to a variable, use backquote
3, multiplication of expr *

Application
Calculate the value of (2+3)*4 to
find the sum of the two parameters of the command line, 20 50

vim oper.sh
#!/bin/bash
#计算(2+3)*4的值
#第一种方式
RES1=$(((2+3)*4))
echo "RES1=$RES1"
#第二种方式,推荐
RES2=$[(2+3)*4]
echo "RES2=$RES2"
#第三种方式
TEMP=`expr 2 + 3`
RES4=`expr $TEMP \* 4`
echo "temp=$TEMP"
echo "RES4=$RES4"
#求出命令行的两个参数的和
SUM=$[$1+$2]
echo "SUM=$SUM"

Results of the
Insert picture description here

Conditional judgment

Basic grammar

[ 内容 ]

Return true if it is not empty, use $? to verify (0 is true, >1 is false)

Commonly used judgment conditions
1, = string comparison
2, comparison of two integers
-lt is less than
-le is less than or equal to
-eq is equal to
-gt is greater than
-ne is not equal to
3, judge according to file permissions
-r has read permission
-w has write The permission
-x has the permission to execute
4, judge according to the file type
-f file exists and is a regular file
-e file exists
-d file exists and is a directory

Judgment of process control

if judgment

if [ 条件判断式 ]
then
代码
fi

Or multi-branch

if[ 条件判断式 ]
then
代码
elif[ 条件判断式 ]
then
代码
fi

case statement

case $变量名 in "值1")
如果变量的值等于1,则执行程序1
;;
"值2")
如果变量的值等于2,则执行程序2
;;

*)
如果变量的值都不是以上的值,则执行此程序
;;
esac

Sample code (remember to use chmod u+x authorization before running in relative path)

vim ifdemo.sh
#!/bin/bash
#判断"ok"是否等于"ok"
if [ "ok" = "ok" ]
then
	echo "equal"
fi
#23是否大于等于22
if [ 23 -ge 22 ]
then
	echo "大于"
fi
#判断/root/shcode/aaa.txt 目录中的文件是否存在
if [ -f /root/shcode/aaa.txt ]
then
	echo "存在"
fi

Results of the
Insert picture description here

vim ifCase.sh
#!/bin/bash
#输入的参数大于等于60,则输出”及格了“,如果小于60,则输出”不及格“
if [ $1 -ge 60 ]
then
	echo "及格了"
elif [ $1 -lt 60 ]
then
	echo "不及格"
fi

Insert picture description here

vim tsetCase.sh
#!/bin/bash
#当命令行参数是1时,输出”周一“,是2时输出”周二“,其他情况输出”other“
case $1 in
"1")
echo "周一"
;;
"2")
echo "周二"
;;
*)
echo "other"
;;
esac

Insert picture description here

The cycle of process control

for loop

Basic Grammar 1

for 变量 in 值123...
do
程序
done

Basic Grammar 2

for (( 初始值;循环控制条件;变量变化 ))
do
程序
done

Code example

vim testFor1.sh
#!/bin/bash
#打印命令行输入的参数
#$*是把参数看成整体,只会输出一句话,$@是把参数区分对待,会输出多次
echo "使用$*获取输入参数"
for i in "$*"
do
	echo "num is $i"
done
echo "================="
echo "使用$@获取输入参数"
for j in "$@"
do
	echo "num is $j"
done

Insert picture description here

vim testFor2.sh
#!/bin/bash
#从1加到输入参数的值输出和
SUM=0
for(( i=1; i<=$1; i++))
do
	SUM=$[$SUM+$i]
done
echo "总和SUM=$SUM"

Insert picture description here
while loop

Basic grammar

while [ 条件判断式 ]
do
程序
done

Code example

vim testWhile.sh
#!/bin/bash
#从命令行输入一个数n,统计从1+..+n的值是多少
SUM=0
i=0
while [ $i -le $1 ]
do
	SUM=$[$SUM+$i]
	#i自增
	i=$[$i+1]
done
echo "执行结果=$SUM"

Insert picture description here

read to read console input

Basic syntax
read option parameters

Option
-p: specify the prompt when reading the value;
-t: specify the waiting time (seconds) when reading the value, if you do not enter the
parameter within the specified time
variable: specify the variable name of the read value

Code example

vim testRead.sh
#!/bin/bash
#读取控制台输入一个NUM1值
read -p "请输入一个数NUM1=" NUM1
echo "NUM1=$NUM1"
#读取控制台输入的NUM2值,在3秒内输入
read -t 3 -p "请输入一个数NUM2=" NUM2
echo "NUM2=$NUM2"

Insert picture description here
Deliberately delay the first time, enter in time for the second time

function

System function

basename

返回完整路径最后/的部分,常用于获取文件名
basename pathname suffix
删掉所有的前缀包括最后一个'/'字符,然后将字符串显示出来
basename string suffix

suffix is ​​the suffix. If suffix is ​​specified, basename will remove suffix in pathname or string.
For example: return the "test.txt" part of /home/aaa/test.txt and "test"
Insert picture description here
dirname
return the end of the full path / before The part, often used to return the path part
dirname Absolute file path: remove the file name (non-directory part) from the given file name containing the absolute path, and then return the remaining path (directory part)

For example: return /home/aaa of /home/aaa/test.txt
Insert picture description here

Custom function

Basic grammar

[function] funname[()]
{
    
    
	Action;
	[return int;]
}	

Call directly write function name: funname [value]

For example: Calculate the sum of input two parameters

vim testFun.sh
#!/bin/bash
#定义函数
function getSum(){
    
    
	SUM=$[$n1+$n2]
	echo "SUM=$SUM"
}
#读取参数
read -p "请输入一个数n1=" n1
read -p "请输入一个数n2=" n2
#调用函数
getSum $n1 $n2

Results of the
Insert picture description here

Database backup case

1. Back up the database zzf to /data/backup/db at 2:30 in the morning every day.
2. The corresponding prompt message can be given at the beginning and end of the
backup. 3. The file after the backup requires the backup time as the file name and packaged into .tar The form of .gz, such as: 2021-03-12_230201.tar.gz
4. While backing up, check whether there is a database file that was backed up 10 days ago, and delete it if there is one

Enter this directory to create the corresponding file

cd /usr/sbin
vim mysql_db_backup.sh
#!/bin/bash
#备份目录
BACKUP=/data/backup/db
#当前时间
DATETIME=$(date +%Y-%m-%d_%H%M%S)
echo $DATETIME
#数据库地址
HOST=localhost
#数据库用户名
DB_USER=root
#数据库密码
DB_PW=zzf123456
#备份的数据库名
DATEBASE=zzf

#创建备份目录,如果不存在,就创建,这里的&&类似于then
[ ! -d "${BACKUP}/${DATETIME}" ] && mkdir -p "${BACKUP}/${DATETIME}"
#备份数据库
mysqldump -u${
    
    DB_USER} -p${
    
    DB_PW} --host=${
    
    HOST} -q -R --databases ${
    
    DATABASE} | gzip > ${
    
    BACKUP}/${
    
    DATETIME}/$DATETIME.sql.gz
#将文件处理成 tar.gz
cd ${
    
    BACKUP}
tar -zcvf $DATETIME.tar.gz ${
    
    DATETIME}
#删除对应的备份目录
rm -rf ${
    
    BACKUP}/${
    
    DATETIME}

#删除10天前的备份文件
find ${
    
    BACKUP} -atime +10 -name "*.tar.gz" -exec rm -rf {
    
    } \;
echo "备份数据库${DATEBASE}成功~"

The results
Insert picture description here
go to the directory you can find that there is a backup file
Insert picture description here
join task scheduling

crontab -e
30 2 * * * /usr/sbin/mysql_db_backup.sh

reference

https://www.bilibili.com/video/BV1Sv411r7vd

Guess you like

Origin blog.csdn.net/qq_43610675/article/details/113433514