第三章 SHELL

1.变量

1.1本地变量

[root@gzh-8 test]# name=values
[root@gzh-8 test]# echo $name
values

本地变量相当于在该shell中创建了一个局部变量,当该shell退出以后局部变量就不存在了

1.2环境变量

环境变量是但你启动一个SHELL时,你的shell会读取环境变量的配置文件查看你当前shell中所存在的环境变量,比如我们在.bash_profile

中设置的环境变量可以直接输出出来.

例如:

[root@gzh-8 ~]# cat .bash_profile 
# .bash_profile
​
# Get the aliases and functions
if [ -f ~/.bashrc ]; then
        . ~/.bashrc
fi
​
# User specific environment and startup programs
​
PATH=$PATH:$HOME/bin
PATH=$PATH:$HOME_DIR/bin
​
export PATH
[root@gzh-8 ~]# echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin:/bin
[root@gzh-8 ~]# 

这里面PATH变量追加了HOME环境变量.

[root@gzh-8 ~]# echo $HOME
/root

还有SHELL会输出我们当前用户使用的shell

[root@gzh-8 ~]# echo $SHELL
/bin/bash

1.3位置变量

位置变量就是当你逐行执行脚本时会根据你命令行中输入的字符进行填充

例如:

[root@gzh-8 test]# cat demo2.sh 
#!/bin/bash
echo "The script's name is : $0"
echo "Parameter : $1"
echo "Parameter : $2"
echo "Parameter : $3"
echo "Parameter : $4"
echo "Parameter : $5"
echo "Parameter : $6"
​
[root@gzh-8 test]# sh demo2.sh 
The script's name is : demo2.sh
Parameter : 
Parameter : 
Parameter : 
Parameter : 
Parameter : 
Parameter : 
[root@gzh-8 test]# sh demo2.sh a b c d e f g
The script's name is : demo2.sh
Parameter : a
Parameter : b
Parameter : c
Parameter : d
Parameter : e
Parameter : f

从你执行shell脚本那一刻开始后面的字符串会传入到脚本的位置变量中.

1.4特殊变量

特殊变量的作用主要是用来查看脚本的运行信息,常用的特殊变量如下:

  • $ # : 传递脚本的参数数量

  • $ *$ @ : 传递脚本的所有参数

  • $ ? : 命令退出状态,0表示正常退出,非0表示异常退出

  • $ $ : 表示进程和PID

例:

[root@gzh-8 test]# cat demo2.sh
#!/bin/bash
echo "The script's name is : $0"
echo "Parameter : $1"
echo "Parameter : $2"
echo "Parameter : $3"
echo "Parameter : $4"
echo "Parameter : $5"
echo "Parameter : $6"
​
#新增内容
​
echo "Parameter count: $#"
echo "ALL parameter: $*"
echo "ALL parameter: $@"
echo "PID: $$"
​
[root@gzh-8 test]# sh demo2.sh a b c d e f g
The script's name is : demo2.sh
Parameter : a
Parameter : b
Parameter : c
Parameter : d
Parameter : e
Parameter : f
Parameter count: 7
ALL parameter: a b c d e f g
ALL parameter: a b c d e f g
PID: 6499

2.符号

2.1引号

'' #单引号 -它将单引号里面的内容作为字符串输出
"" #双引号 -它可以包含单引号,和单引号作用一样
`` #反引号 -它可以进行命令替换可以和双引号结合例如输出时间
# 例:
[root@gzh-8 test]# echo "Today is `date`"
Today is 2023年 09月 21日 星期四 07:39:16 EDT

2.2通配符

1.通配符"*"

它可以通配0个或多个字符.

[root@gzh-8 test]# ls -d /etc/sys*
/etc/sysconfig    /etc/sysctl.d  /etc/system-release
/etc/sysctl.conf  /etc/systemd   /etc/system-release-cpe

2.通配符"?"

它每次只能通配一个字符

[root@gzh-8 test]# ls -d /etc/??
/etc/bk  /etc/pm
[root@gzh-8 test]# ls -d /etc/???
/etc/dnf  /etc/lvm  /etc/pki  /etc/rpm  /etc/ssl  /etc/xdg
/etc/gss  /etc/opt  /etc/rpc  /etc/ssh  /etc/X11  /etc/yum

3.通配符"[]"

它可以查找[]里面给定范围的字符

[root@gzh-8 test]# ls /etc/[f-h]*.conf
/etc/fuse.conf  /etc/host.conf

4.通配符"[!]"

它表示出了[]里面的字符,与其他任意字符匹配

[root@gzh-8 test]# ls -d /etc/y*[!.conf]
/etc/yum  /etc/yum.repos.d

2.3连接符

1.";"连接符

它的作用是可以在一行中分步执行多条命令

例:

[root@gzh-8 etc]# cd /root/test;ls -a;pwd
.  ..  demo1.sh  demo2.sh
/root/test
[root@gzh-8 test]# 

2."&&"连接符

它遵循逻辑关系,只有当前一个命令运行成功以后后面的命令才会执行.

[root@gzh-8 test]# cd /test && cd /
-bash: cd: /test: 没有那个文件或目录

3."||"连接符

它也遵循逻辑关系,不管前面的运行成功与否后面的都会执行.

[root@gzh-8 test]# cd /test || cd /
-bash: cd: /test: 没有那个文件或目录
[root@gzh-8 /]#

3.正则表达式

3.1元字符

这些元字符和通配符用法都差不多,这里只写几个例子

  1. 限定符"*"

    [root@gzh-8 /]# ls ~/*
    /root/anaconda-ks.cfg  /root/test.tar.bz2
    /root/test.tar         /root/test.tar.gz
    
    /root/gzh:
    demo1.sh  test.tar  zgh
    
    /root/PATH_DIR:
    
    /root/test:
    demo1.sh  demo2.sh

  2. 点字符"."

    只能匹配一个字符

  3. 行首定位符"^"

    # 匹配以sys开头的文件
    [root@gzh-8 ~]# ls /etc/ |grep "^sys"
    sysconfig
    sysctl.conf
    sysctl.d
    systemd
    system-release
    system-release-cpe

  4. 行尾定位符"$"

    # 匹配以conf结尾的文件
    [root@gzh-8 ~]# ls /etc | grep conf$
    chrony.conf
    dracut.conf
    fuse.conf
    host.conf
    idmapd.conf
    kdump.conf
    krb5.conf
    ...
  5. 字符组"[]"

    # 匹配指定范围字符串和通配符[]用法一样
    # 匹配rc开头且后面字符在[0-9]之间的
    [root@gzh-8 ~]# ls /etc/ |grep "^rc[0-9]"
    rc0.d
    rc1.d
    rc2.d
    rc3.d
    rc4.d
    rc5.d
    rc6.d
  6. 排除型字符组"[^]"

    []用法相反.

3.2扩展正字表达式元字符

  1. 限定符"+"

    匹配一次或多次字符

  2. 限定符"?"

    只能匹配一次

  3. "|"和"()"符号

    "|"符号实现正则表达式之间的"或"运算,格式如下

    表达式1 | 表达式2 | ... | 表达式n

    "()"符号可以和|结合使用

    [root@gzh-8 ~]# ls /etc | egrep "(ssh|ssl|^yum)"
    libssh
    ssh
    ssl
    yum
    yum.conf
    yum.repos.d

4.文本处理工具

4.1 grep

它全称的意思是全局搜索正则表达式并打印文本行

grep常用选项

  • -i :忽略大小写进行匹配。

  • -v :反向查找,只打印不匹配的行。

  • -n :显示匹配行的行号。

  • -r :递归查找子目录中的文件。

  • -l :只打印匹配的文件名。

  • -c :只打印匹配的行数。

例:

[root@gzh-8 ~]# grep -n ^# /etc/sysctl.conf
1:# sysctl settings are defined through files in
2:# /usr/lib/sysctl.d/, /run/sysctl.d/, and /etc/sysctl.d/.
3:#
4:# Vendors settings live in /usr/lib/sysctl.d/.
5:# To override a whole file, create a new file with the same in
6:# /etc/sysctl.d/ and put new settings there. To override
7:# only specific settings, add a file with a lexically later
8:# name in /etc/sysctl.d/ and put new settings there.
9:#
10:# For more information, see sysctl.conf(5) and sysctl.d(5).

[root@gzh-8 ~]# grep -c ^$ /etc/yum.conf
0
[root@gzh-8 ~]# grep -c ^[^$] /etc/yum.conf
6

4.2 sed

sed 可依照脚本的指令来处理、编辑文本文件。

Sed 主要用来自动编辑一个或多个文件、简化对文件的反复操作、编写转换程序等。

常用参数

  • -e<script>或--expression=<script> 以选项中指定的script来处理输入的文本文件。

  • -f<script文件>或--file=<script文件> 以选项中指定的script文件来处理输入的文本文件。

  • -h或--help 显示帮助。

  • -n或--quiet或--silent 仅显示script处理后的结果。

  • -V或--version 显示版本信息。

编辑命令

  • a :新增, a 的后面可以接字串,而这些字串会在新的一行出现(目前的下一行)~

  • c :取代, c 的后面可以接字串,这些字串可以取代 n1,n2 之间的行!

  • d :删除,因为是删除啊,所以 d 后面通常不接任何东东;

  • i :插入, i 的后面可以接字串,而这些字串会在新的一行出现(目前的上一行);

  • p :打印,亦即将某个选择的数据印出。通常 p 会与参数 sed -n 一起运行~

  • s :取代,可以直接进行取代的工作哩!通常这个 s 的动作可以搭配正则表达式!例如 1,20s/old/new/g 就是啦!

例:

# 先编辑文件testfile
[root@gzh-8 test]# cat testfile 
HELLO LINUX!  
Linux is a free unix-type opterating system.  
This is a linux testfile!  
Linux test 
Google
Taobao
Runoob
Tesetfile
Wiki

# 在 testfile 文件的第四行后添加一行,并将结果输出到标准输出
[root@gzh-8 test]# sed -e 4a\gzh大帅哥 testfile 
HELLO LINUX!  
Linux is a free unix-type opterating system.  
This is a linux testfile!  
Linux test 
gzh大帅哥
Google
Taobao
Runoob
Tesetfile
Wiki
# 将 testfile 的内容列出并且列印行号,同时,请将第 2~5 行删除!
[root@gzh-8 test]# nl testfile | sed '2,5d'
     1  HELLO LINUX!  
     6  Taobao
     7  Runoob
     8  Tesetfile
     9  Wiki

4.3 awk

AWK 是一种处理文本文件的语言,是一个强大的文本分析工具。

基本格式

awk [选项] pattern {actions} 文件

常用选项:

  • -F 指定输入文件折分隔符,fs是一个字符串或者是一个正则表达式,如-F:。

  • -v 赋值一个用户定义变量。

  • -f 从脚本文件中读取awk命令。

awk使用演示:

# 先创建一个test文件
[root@gzh-8 test]# cat test
zhangsan        88      76      90      83
lisi    100     69      89      84
xiangwang       100     69      89      84
xiangming       100     69      89      84
lili    100     69      89      84
xiaohaong       100     69      89      84
# 编写awk脚本文件
[root@gzh-8 test]# cat awk.sh 
#!/bin/bash
result=`awk '$2>80 {print}' test`
echo "$result"
[root@gzh-8 test]# sh awk.sh 
zhangsan        88      76      90      83
lisi    100     69      89      84
xiangwang       100     69      89      84
xiangming       100     69      89      84
lili    100     69      89      84
xiaohaong       100     69      89      84
[root@gzh-8 test]# cat awk.sh 
#!/bin/bash
result=`awk '/^x/ {print}' test`
echo "$result"
[root@gzh-8 test]# sh awk.sh 
xiangwang       100     69      89      84
xiangming       100     69      89      84
xiaohaong       100     69      89      84
[root@gzh-8 test]# cat awk.sh 
#!/bin/bash
result=`awk '/^(zhang|li)/ {print}' test`
echo "$result"
[root@gzh-8 test]# sh awk.sh 
zhangsan        88      76      90      83
lisi    100     69      89      84
lili    100     69      89      84
[root@gzh-8 test]# cat awk.sh 
#!/bin/bash
result=`awk '/^li/ && $2>80 {print}' test`
echo "$result"
[root@gzh-8 test]# sh awk.sh 
lisi    100     69      89      84
lili    100     69      89      84

5.Shell脚本

5.1判断结构

  1. if结构

    格式

    if expression
    then
    	命令语句
    fi
    
    或
    
    if expression; then
    	命令语句
    fi

    判断当前目录下面是否存在test文件

    [root@gzh-8 test]# cat if.sh 
    #!/bin/bash
    if [ -e test ]; then
            echo "test存在"
    fi
    [root@gzh-8 test]# sh if.sh 
    test存在
  2. if/else结构

    格式

    if expression
    then
    	命令语句1
    else
    	命令语句2
    fi

    读取用户输入的字符串,如果字符串为空,则输入空,若不为空则输出字符串

    [root@gzh-8 test]# cat ifelse.sh 
    #!/bin/bash
    echo "请输入字符串: "
    read str
    if [ -z "$str" ]; then
            echo "字符串为空"
    else
            echo $str
    fi
    
    [root@gzh-8 test]# sh ifelse.sh 
    请输入字符串: 
    
    字符串为空
    [root@gzh-8 test]# sh ifelse.sh 
    请输入字符串: 
    gzh
    gzh
    1. if/elif/else结构

      格式

      if expression1; then
      	命令语句1
      elif expression2; then
      	命令语句2
      ...
      fi

      读取输入的学生成绩,判断成绩等级

      [root@gzh-8 test]# cat ifelif.sh 
      #!/bin/bash
      echo "请输入成绩: "
      read score
      if [ $score -lt 0 -o $score -gt 100 ]; then
              echo error score
      elif [ $score -ge 90 ]; then
              echo A
      elif [ $score -ge 80 ]; then
              echo B
      elif [ $score -ge 70 ]; then
              echo C
      else 
              echo D
      fi
      [root@gzh-8 test]# sh ifelif.sh 
      请输入成绩: 
      90
      A
    2. case结构

      通过用户输入的整数值判断是周几

      [root@gzh-8 test]# cat case.sh
      #!/bin/bash
      echo "请输入:"
      read week
      case "$week" in
      1)
              echo "星期一";;
      2)      
              echo "星期二";;
      3)      
              echo "星期三";;
      4)      
              echo "星期四";;
      5)      
              echo "星期五";;
      6)      
              echo "星期六";;
      7)      
              echo "星期天";;
      *)      
              echo "错误";;
      esac
      [root@gzh-8 test]# sh case.sh 
      请输入:
      1
      星期一

5.2 循环结构

  1. for循环

    格式

    for var in {list}
    do
    	命令语句
    done

    循环输出1-5

    [root@gzh-8 test]# cat for.sh 
    #!/bin/bash
    for var in 1 2 3 4 5
    do
            echo $var
    done
    [root@gzh-8 test]# sh for.sh 
    1
    2
    3
    4
    5
  2. while循环

    格式

    while expression
    do
    	命令语句
    done

    循环输出1-5

    [root@gzh-8 test]# cat while.sh 
    #!/bin/bash
    num=1
    while (($num<=5))
    do
            echo $num
            let num++
    done
    [root@gzh-8 test]# sh while.sh 
    1
    2
    3
    4
    5
  3. until循环

    格式

    until expression
    do
    	命令语句
    done

    循环输出1-5

    [root@gzh-8 test]# cat until.sh 
    #!/bin/bash
    num=1
    until [ $num -gt 5 ]
    do
            echo $num
            let num++
    done
    [root@gzh-8 test]# sh until.sh 
    1
    2
    3
    4
    5
    # 要注意的是[]里面的空格不能省略

5.3break与continue

  1. break

    当num变量值为3时退出循环

    [root@gzh-8 test]# cat break.sh 
    #!/bin/bash
    num=1
    until [ $num -gt 5 ]
    do
            echo $num
            if [ $num -eq 3 ]; then
                    break
            fi
            let num++
    done
    echo "now,exit until circulation"
    [root@gzh-8 test]# sh break.sh 
    1
    2
    3
    now,exit until circulation
  2. continue

    输出1-50内可以被5整除的数

    [root@gzh-8 test]# cat continue.sh 
    #!/bin/bash
    for num in {1..50}
    do
            let temp=num%5
            if [ $temp -ne 0 ]; then
                    continue
            fi
            echo $num
    done
    [root@gzh-8 test]# sh continue.sh 
    5
    10
    15
    20
    25
    30
    35
    40
    45
    50

6.脚本实例

6.1模拟用户登录

[root@gzh-8 test]# cat -n dl.sh 
     1  #!/bin/bash
     2  read -ep "请输入用户名: " name
     3  if [ "$name" == "gzh" ]; then
     4          read -ep "请输入密码: " passwd       
     5          if [ "$passwd" == "guo123" ]; then
     6                  echo "登陆成功"
     7          else
     8                  echo "密码错误!"
     9          fi
    10  else 
    11          echo "用户名错误!"
    12  fi
[root@gzh-8 test]# sh dl.sh 
请输入用户名: gzh
请输入密码: guo123
登陆成功
[root@gzh-8 test]# sh dl.sh 
请输入用户名: guo
用户名错误!
[root@gzh-8 test]# sh dl.sh 
请输入用户名: gzh
请输入密码: gzh
密码错误!

6.2监控系统运行情况

[root@gzh-8 test]# cat -n system.sh 
     1  #!/bin/bash
     2  echo "(1)*****************************************"
     3  date;
     4  echo "Active User: "
     5  w
     6  echo "(2)*****************************************"
     7  echo "Linux process: "
     8  top -b | head -6
     9  echo "(3)*****************************************"
    10  echo "Disk an Memory use ratio: "
    11  df -h |xargs | awk '{print "Fress/total disk: " $11"/"$9}'
    12	free -m |xargs | awk '{print "Fress/total memory: " $17"/"$8"MB"}'
    13  echo "(4)*****************************************"
    14  echo "All Processec: "
    15  ps auxf
    16  echo "(5)*****************************************"
    17  echo "vmstat: "
    18  vmstat 1 5
    19  echo "(6)*****************************************"
    20  echo "Scan the entire subnet: "
    21  nmap 192.168.88.*
    22  echo "(7)*****************************************"
    23  echo "socket for each process: "
    24  ss -pl
  1. 2-5行代码显示主机时间和当前用户信息

  2. 6-8行代码用来显示CPU使用请款

  3. 9-12行用来显示硬盘与内存的使用情况

  4. 13-15行显示终端下的所有进程

  5. 16-18用来显示虚拟内存的使用情况

  6. 19-21用来扫描和主机一个段下的所有主机

  7. 22-24用来查看每个进程显示的具体socket

6.3备份MySQL数据库

第一步安装MySQL

[root@gzh-8 test]# wget https://dev.mysql.com/get/mysql80-community-release-el8-1.noarch.rpm
--2023-09-21 23:49:12--  https://dev.mysql.com/get/mysql80-community-release-el8-1.noarch.rpm
正在解析主机 dev.mysql.com (dev.mysql.com)... 223.119.225.252, 2402:4f00:4002:194::2e31, 2402:4f00:4002:182::2e31
正在连接 dev.mysql.com (dev.mysql.com)|223.119.225.252|:443... 已连接。
已发出 HTTP 请求,正在等待回应... 302 Moved Temporarily
位置:https://repo.mysql.com//mysql80-community-release-el8-1.noarch.rpm [跟随至新的 URL]
--2023-09-21 23:49:18--  https://repo.mysql.com//mysql80-community-release-el8-1.noarch.rpm
正在解析主机 repo.mysql.com (repo.mysql.com)... 23.49.202.55, 2402:4f00:4001:1af::1d68, 2402:4f00:4001:186::1d68
正在连接 repo.mysql.com (repo.mysql.com)|23.49.202.55|:443... 已连接。
已发出 HTTP 请求,正在等待回应... 200 OK
长度:30388 (30K) [application/x-redhat-package-manager]
正在保存至: “mysql80-community-release-el8-1.noarch.rpm”

mysql80-community-release- 100%[======================================>]  29.68K  60.2KB/s  用时 0.5s    

2023-09-21 23:49:24 (60.2 KB/s) - 已保存 “mysql80-community-release-el8-1.noarch.rpm” [30388/30388])

[root@gzh-8 test]# yum install mysql80-community-release-el8-1.noarch.rpm
上次元数据过期检查:0:07:57 前,执行于 2023年09月21日 星期四 23时41分52秒。
错误:
 问题: package mysql80-community-release-el8-1.noarch conflicts with mysql57-community-release provided by mysql57-community-release-el7-7.noarch
  - conflicting requests
  - problem with installed package mysql57-community-release-el7-7.noarch
(尝试在命令行中添加 '--allowerasing' 来替换冲突的软件包 或 '--skip-broken' 来跳过无法安装的软件包 或 '--nobest' 来不只使用软件包的最佳候选)
[root@gzh-8 test]# yum install mysql80-community-release-el8-1.noarch.rpm --allowerasing
上次元数据过期检查:0:08:23 前,执行于 2023年09月21日 星期四 23时41分52秒。
依赖关系解决。
==========================================================================================================
 软件包                               架构              版本                仓库                     大小
==========================================================================================================
安装:
 mysql80-community-release            noarch            el8-1               @commandline             30 k
移除依赖的软件包:
 mysql57-community-release            noarch            el7-7               @System                 7.8 k

事务概要
==========================================================================================================
安装  1 软件包
移除  1 软件包

总计:30 k
确定吗?[y/N]: y
下载软件包:
运行事务检查
事务检查成功。
运行事务测试
事务测试成功。
运行事务
  准备中  :                                                                                           1/1 
  安装    : mysql80-community-release-el8-1.noarch                                                    1/2 
  删除    : mysql57-community-release-el7-7.noarch                                                    2/2 
  验证    : mysql80-community-release-el8-1.noarch                                                    1/2 
  验证    : mysql57-community-release-el7-7.noarch                                                    2/2 

已安装:
  mysql80-community-release-el8-1.noarch                                                                  
已移除:
  mysql57-community-release-el7-7.noarch                                                                  

完毕!
[root@gzh-8 test]# yum repolist enabled | grep "mysql.*-community.*"
mysql-connectors-community       MySQL Connectors Community
mysql-tools-community            MySQL Tools Community
mysql80-community                MySQL 8.0 Community Server
[root@gzh-8 test]# yum module disable mysql
MySQL 8.0 Community Server                                                236 kB/s | 3.2 MB     00:13    
MySQL Connectors Community                                                8.4 kB/s | 102 kB     00:12    
MySQL Tools Community                                                      59 kB/s | 794 kB     00:13    
上次元数据过期检查:0:00:01 前,执行于 2023年09月21日 星期四 23时51分24秒。
依赖关系解决。
==========================================================================================================
 软件包                   架构                    版本                     仓库                      大小
==========================================================================================================
禁用模块:
 mysql                                                                                                   

事务概要
==========================================================================================================

确定吗?[y/N]: y
完毕!
[root@gzh-8 test]# yum install mysql-community-server
上次元数据过期检查:0:00:42 前,执行于 2023年09月21日 星期四 23时51分24秒。
依赖关系解决。
==========================================================================================================
 软件包                          架构    版本                                    仓库                大小
==========================================================================================================
安装:
 mysql-community-server          x86_64  8.0.34-1.el8                            mysql80-community   64 M
安装依赖关系:
 mysql-community-client          x86_64  8.0.34-1.el8                            mysql80-community   16 M
 mysql-community-client-plugins  x86_64  8.0.34-1.el8                            mysql80-community  3.5 M
 ...
安装弱的依赖:
 perl-IO-Socket-IP               noarch  0.39-5.el8                              AppStream           47 k
 perl-IO-Socket-SSL              noarch  2.066-4.module_el8.3.0+410+ff426aa3     AppStream          298 k
 perl-Mozilla-CA                 noarch  20160104-7.module_el8.3.0+416+dee7bcef  AppStream           15 k
启用模块流:
 perl                                    5.26                                                            
 perl-IO-Socket-SSL                      2.066                                                           
 perl-libwww-perl                        6.34                                                            

事务概要
==========================================================================================================
安装  48 软件包

总下载:101 M
安装大小:452 M
确定吗?[y/N]: y
下载软件包:
(1/48): perl-Carp-1.42-396.el8.noarch.rpm                                 5.7 kB/s |  30 kB     00:05    
(2/48): perl-Data-Dumper-2.167-399.el8.x86_64.rpm                          11 kB/s |  58 kB     00:05    
(3/48): net-tools-2.0-0.52.20160912git.el8.x86_64.rpm                      57 kB/s | 322 kB     00:05    
(4/48): perl-Errno-1.28-420.el8.x86_64.rpm                             ...
...                                                                

完毕!
[root@gzh-8 test]# systemctl start mysqld
[root@gzh-8 test]# systemctl enable mysqld


# 注意: Mysql安装完以后会生成随机密码,查看随机密码并更改他
[root@gzh-8 test]# grep 'temporary password' /var/log/mysqld.log
2023-09-22T03:54:04.925109Z 6 [Note] [MY-010454] [Server] A temporary password is generated for root@localhost: I1!j8ZBk8f(&
[root@gzh-8 test]# mysql -uroot -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 10
Server version: 8.0.34

Copyright (c) 2000, 2023, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'Guozhihang0206.';
Query OK, 0 rows affected (0.01 sec)

mysql> set global validate_password.policy=low;
Query OK, 0 rows affected (0.00 sec)

mysql> set global validate_password.length=4;
Query OK, 0 rows affected (0.00 sec)

mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'guo123';
Query OK, 0 rows affected (0.00 sec)

要备份数据库先确定备份的数据库列表,这里新建一个数据库列表test

[root@gzh-8 test]# mysql -u root -pguo123
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 19
Server version: 8.0.34 MySQL Community Server - GPL

Copyright (c) 2000, 2023, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> create database test;
Query OK, 1 row affected (0.01 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
| test               |
+--------------------+
5 rows in set (0.00 sec)

mysql> exit
Bye

编写sqlbak.sh脚本文件

[root@gzh-8 test]# cat sqlbak.sh 
#!/bin/bash
#完成数据库的定时备份
#备份的路径
BACKUP=/root/mysqlbak
#当前的时间作为文件名
DATETIME=$(date +%Y_%m_%d_%H%M%S)
#可以输出变量调试
#echo ${DATETIME}
echo "==========开始备份==========="
echo "备份的路径是 $BACKUP/$DATETIME.tar.gz"

#主机
HOST=localhost
#用户名
DB_USER=root
#密码
DB_PWD=guo123
#备份数据库名
DATABASE="test"
#创建备份的路径
#如果备份的路径文件夹存在就使用,否则创建
[ ! -d "$BACKUP/$DATETIME"  ]  && mkdir -p "$BACKUP/$DATETIME" 
#执行mysql的备份数据库的指令
mysqldump -u${DB_USER} -p${DB_PWD} --host=$HOST  $DATABASE | gzip  > $BACKUP/$DATETIME/$DATETIME.sql.gz
#打包备份文件
cd $BACKUP
tar -zcvf  $DATETIME.tar.gz  $DATETIME
#删除临时目录
rm -rf  $BACKUP/$DATETIME

#删除10天前的备份文件(-exec rm -rf {} \是固定写法,删除查询出来的数据)
find $BACKUP -mtime +10 -name  "*.tar.gz" -exec rm -rf {} \;
echo "==========备份完成==========="
[root@gzh-8 test]# sh sqlbak.sh 
==========开始备份===========
备份的路径是 /root/mysqlbak/2023_09_22_032545.tar.gz
mysqldump: [Warning] Using a password on the command line interface can be insecure.
2023_09_22_032545/
2023_09_22_032545/2023_09_22_032545.sql.gz
==========备份完成===========
[root@gzh-8 test]# ls ../mysqlbak/
2023_09_22_032545.tar.gz