第二周整合

目录

壹 · 常见的文本处理工具

1 文本编辑工具-vim

1.1 vim的格式

1.2 vim的部分参数

1.3 vim的基础用法

2.文本查看工具 

2.1 文本文件查看工具

2.1.1 cat

2.1.2 nl

2.1.3 tac

 2.2 非文本文件查看工具

hexdump

2.3 分页查看工具

2.3.1 more

2.3.2 less

2.4 查看文件前/后几行

2.4.1 head

2.4.2 tail

2.5 文本切割/合并工具

2.5.1 cut

2.5.2 paste

3 文本分析工具

3.1 文本统计-wc

3.2 文本排序-sort

3.3 文本去重-uniq

3.4 文本比较-diff

贰 · 正则表达式和文件处理

1 正则表达式

1.1 什么是正则表达式

1.2 基础正则表达式

2 文本处理三剑客

2.1 grep

2.2 sed

2.3 awk

3 文件格式化处理

3.1 格式化打印-printf

3.2 文本对比工具-diff

4 文件查找

4.1 locate

4.2 find

叁 · Linux文件系统

1 Linux磁盘分区表

1.1 MBR

1.2 GTP

2 Linux磁盘管理

2.1 lsblk

2.2 fdisk

2.3 格式化

2.4 mount

2.5 umount

2.6 swapon

2.8 swapoff

肆 · 初识Shell

1 认识shell

1.1 什么是shell

1.2 shell脚本

2 shell变量

2.1 变量的命名要求

2.2 变量的使用与设置

2.2.1 变量的分类

2.2.2 变量的使用

2.2.3 变量的赋值

3 编写脚本

3.1 shell脚本创建过程

3.2 第一个shell脚本

3.3 用shell解鸡兔同笼

3.3.1 read

3.3.2 解题

3.4 用shell脚本批量创建用户

3.4.1 for的语法

3.4.2 if的语法

3.4.3 创建100个用户


壹 · 常见的文本处理工具

1 文本编辑工具-vim

1.1 vim的格式
usage: vim [arguments] [file ..]       edit specified file(s)
   or: vim [arguments] -               read text from stdin
   or: vim [arguments] -t tag          edit file where tag is defined
   or: vim [arguments] -q [errorfile]  edit file with first error
1.2 vim的部分参数
-R 只读模式 (同 "view")
-Z 限制模式 (同 "rvim")
-m 不允许修改(写入文件)
-M 不允许修改文本
-b 二进制模式
-D 调试模式
-n 不使用交换文件,只使用内存
-A 以 Arabic 模式启动
-H 以 Hebrew 模式启动
-F 以 Farsi 模式启动
-T <terminal> 设定终端类型为 <terminal>
+  从文件末尾开始
1.3 vim的基础用法

参考之前的linux基础第五章

2.文本查看工具 

2.1 文本文件查看工具
2.1.1 cat

cat(英文全拼:concatenate)命令用于连接文件并打印到标准输出设备上。

Usage: cat [OPTION]... [FILE]...

Options:
  -A, --show-all           等同于-vET
  -b, --number-nonblank    和-n类似,但空白行无编号
  -e                       等同于-vE
  -E, --show-ends          在每行结束处显示$。
  -n, --number             由1开始对所有输出的行数编号。
  -s, --squeeze-blank      当遇到有连续两行以上的空白行,就代换为一行的空白行。
  -t                       等同于-vT
  -T, --show-tabs          将 TAB 字符显示为 ^I。
  -v, --show-nonprinting   使用 ^ 和 M- 符号,除了 LFD 和 TAB 之外。

配合重定向可完成一些特殊操作,例如:

cat 1.txt > 2.txt     #将1.txt的内容重定向到2.txt
cat 1.txt >> 2.txt    #将1.txt的内容追加到2.txt中
cat > 3.txt           #重定向输入到3.txt
cat >> 3.txt          #以追加的方式重定向到3.txt

Eg:
[root@localhost ~]# cat 3.txt 
0
[root@localhost ~]# cat > 3.txt
1
^C
[root@localhost ~]# cat 3.txt 
1
[root@localhost ~]# cat >> 3.txt 
2
3
^C     
[root@localhost ~]# cat 3.txt 
1
2
3
[root@localhost ~]#
2.1.2 nl

不加参数的效果等同于cat -b

Usage: nl [OPTION]... [FILE]...

Eg:
[root@localhost ~]# echo -e "123\n456\n\n789" > ./1.txt  
[root@localhost ~]# nl 1.txt 
     1  123
     2  456
       
     3  789
[root@localhost ~]# 
2.1.3 tac

从下往上逐行输出文件内容

[root@localhost ~]# echo -e "123\n456\n\n789" > ./1.txt
[root@localhost ~]# tac 1.txt 
789

456
123
[root@localhost ~]#
 2.2 非文本文件查看工具
hexdump

hexdump是Linux下的一个二进制文件查看工具,它可以将二进制文件转换为ASCII、八进制、十进制、十六进制格式进行查看

Usage: hexdump [options] <file>...

Options:
 -b, --one-byte-octal      每个字节显示为8进制
 -c, --one-byte-char       每个字节显示为ASCII字符
 -C, --canonical           每个字节显示为16进制和相应的ASCII字符
 -d, --two-bytes-decimal   每两个字节显示为10进制
 -o, --two-bytes-octal     每两个字节八进制显示
 -x, --two-bytes-hex       每两个节十六进制显示
2.3 分页查看工具
2.3.1 more

类似 cat ,不过会以一页一页的形式显示,更方便使用者逐页阅读

Usage: more [options] <file>...

Options:
 -c          不以卷动的方式显示每一页,先显示内容再清除萤幕
 -p          不以卷动的方式显示每一页,先清除萤幕再显示内容
 -s          当遇到有连续两行以上的空白行,就替换为一行空白行
 -u          不显示下划线
 -<number>   一次显示的行数
 +<number>   从第<number>行开始显示
2.3.2 less

与more类似,但可以随意浏览文件。支持翻页和搜索,支持向上翻页和向下翻页。

Usage: more [options] <file>

Options:
  -e 当文件显示结束后,自动退出
  -f 强制打开特殊文件,例如外围设备代号、目录和二进制文件
  -g 只标志最后搜索的关键词
  -i 忽略搜索时的大小写
  -m 显示类似more命令的百分比
  -N 显示每行的行号
  -o <文件名> 将less 输出的内容在指定文件中保存起来
  -Q 不使用警告音
  -s 当遇到有连续两行以上的空白行,就替换为一行空白行
  -S 将长度超过屏幕宽度的行截断而不是换行。可用左右键查看超出宽度的部分
  -x <数字> 将"tab"键显示为规定的数字空格
2.4 查看文件前/后几行
2.4.1 head
Usage: head [OPTION]... [FILE]...    #head默认为 head -10

Options:
  -n   显示文件前n行
  -c n 显示文件前n个字节

Eg:
[root@localhost ~]# head /etc/passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
...
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
[root@localhost ~]#

[root@localhost ~]# head -3 /etc/passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
[root@localhost ~]#
2.4.2 tail
Usage: tail [OPTION]... [FILE]...    #tail默认为 tail -10

Options:
  -n   显示文件后n行
  -c n 显示n个字节
  -f   循环读取

Eg:
[root@localhost ~]# tail /etc/group 
libstoragemgmt:x:992:
setroubleshoot:x:991:
...
tcpdump:x:72:
xiao:x:1000:
[root@localhost ~]#

[root@localhost ~]# tail -3 /etc/group
slocate:x:21:
tcpdump:x:72:
xiao:x:1000:
[root@localhost ~]# 
2.5 文本切割/合并工具
2.5.1 cut

按列抽取文本

Usage: cut OPTION... [FILE]...

Options:
  -b :以字节为单位进行分割,但字节位置将忽略多字节字符边界
  -c :以字符为单位进行分割。
  -d :自定义分隔符,默认为制表符。
  -f :与-d一起使用,指定显示哪个区域
  -n :取消分割多字节字符,和-b标志一起使用

Eg:
  cut -d: -f2,4-5 /etc/passwd    #按冒号分割/etc/passwd中的内容,显示第2、4-5列的内容
2.5.2 paste

合并多个文件同行号的列到同一行

Usage: paste [OPTIONS]... [FILE]...

Options:
  -d 指定分隔符,默认为TAB
  -s 所有行合成一行显示

3 文本分析工具

3.1 文本统计-wc

计算文件的Byte数、字数、或是列数

Usage: wc [OPTION]... [FILE]...
  or:  wc [OPTION]... --files0-from=F

Options:
-c, --bytes 只显示字节数。
-l, --lines 显示行数。
-w, --words 只显示字数。

Eg:
[root@localhost ~]# cat 2.txt 
1
2
3
4
5
6
7
8
9
10
[root@localhost ~]# wc 2.txt 
10 10 21 2.txt    #从左到右分别是行数 单词数 字节数 文件名
[root@localhost ~]#
3.2 文本排序-sort

针对文本文件的内容,以行为单位排序后输出,不会改变源文件

Usage: sort [OPTION]... [FILE]...
  or:  sort [OPTION]... --files0-from=F

Options:
  -r 反序整理
  -R 随机排序
  -n 执行按数字大小排序
  -h 人类可读排序,如2k、1G
  -f 排序时忽略大小写
3.3 文本去重-uniq

从输入中删除前后相接的重复的行

Usage: uniq [OPTION]... [INPUT [OUTPUT]]

Options:
  -c 显示每行重复出现的次数
  -d 只显示重复过的行
  -u 只显示没重复过的行

Eg:
[root@localhost ~]# cat 2.txt 
1
2
2
3
3
3
4
[root@localhost ~]# uniq 2.txt 
1
2
3
4
[root@localhost ~]# uniq -c 2.txt 
      1 1
      2 2
      3 3
      1 4
[root@localhost ~]#
3.4 文本比较-diff
#文件完全一样时没有反馈
[root@localhost ~]# cat 2.txt > 3.txt
[root@localhost ~]# diff 2.txt 3.txt
[root@localhost ~]# 
#文件不同时会反会不同的部分
[root@localhost ~]# echo 1234 >> 2.txt 
[root@localhost ~]# echo 4321 >> 3.txt      
[root@localhost ~]# diff 2.txt 3.txt 
8c8
< 1234
---
> 4321
[root@localhost ~]#

贰 · 正则表达式和文件处理

1 正则表达式

1.1 什么是正则表达式

正则表达式(Regular Expression,或称为常规表示法)是通过一些特殊字符的排列,用以查找、替换、删除一行或多行文字字符串的表达式。

正则表达式不是一个工具程序,而是一个字符串组处理的标准依据。支持正则表达式的工具有很多,例如vi、grep、sed、awk。

1.2 基础正则表达式

需要注意的是正则表达式和bash中的通配符是不一样的,不要弄混。

下面是正则表式中的一些特殊符号:

特殊符号代表意义
[:alnum:]代表英文大小写字符及数字,即0~9,A~Z,a~z
[:alpha:]代表任何英文大小写字符,即A~Z,a~z
[:blank:]代表空格键与Tab键
[:cntrl:]代表键盘上面 控制按键,包括CR、LF、Tab、Del等
[:digit:]代表数字,即0~9
[:lower:]代表小写字符,即a~z
[:print:]代表任何可以被打印出来的字符
[:punct:]代表标点符号,即:;“?!等
[:upper:]代表所有大写字符,即A~Z
[:space:]任何会产生空白的字符,包括空格、Tab、CR等
[:xdigit:]代表十六进制的数字类型,包括0~9、A~F、a~f

2 文本处理三剑客

2.1 grep

用于查找文件里符合条件的字符串或正则表达式

Usage: grep [OPTION]... PATTERN [FILE]...

Options:
  --color=auto              对匹配到的文本着色处理
  -e, --regexp=PATTERN      指定字符串做为查找文件内容的样式
  -E, --extended-regexp     使用扩展正则表达式,相当于egrep
  -f, --file=FILE           file根据模式文本处理
  -i, --ignore-case         忽略字符大小写的差别
  -v, --invert-match        显示不包含匹配文本的所有行
  -m, --max-count=NUM       匹配几行后停止
  -n, --line-number         显示符合条件的行的行号
  -o, --only-matching       只显示匹配到的字符串
  -q, --quiet, --silent     不显示任何信息
  -c, --count               计算符合样式的列数
  -B, --before-context=NUM  除了显示符合样式的那一行之外,还显示该行之前的内容
  -A, --after-context=NUM   除了显示符合样式的那一列之外,还显示该行之后的内容
  -C, --context=NUM         除了显示符合样式的那一行之外,还显示该行之前之后的内容

Eg:
#查看字符串在文件的第几行
[root@localhost ~]# grep -c processor /proc/cpuinfo 
1
[root@localhost ~]# head -1 /proc/cpuinfo 
processor       : 0
[root@localhost ~]#

#可以取两个文件中的相同行
[root@localhost ~]# cat 1.txt
1
2
a
b
c
[root@localhost ~]# cat 2.txt
1
2
3
4
[root@localhost ~]# grep -f 1.txt 2.txt 
1
2
[root@localhost ~]# 
2.2 sed

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

Usage: sed [OPTION]... {script;script;...} [input-file]...

Options:
  -n 不输出模式空间内容到屏幕,即不自动打印
  -e 多点编辑
  -f 从指定文件中读取编辑脚本
  -i 备份文件并原处编辑
  -s 将多个文件视为独立文件,而不是单个连续的长文件流

COMMAND SYNOPSIS:
  a 在指定行后面追加内容
  c 取代, c 的后面可以接字串,这些字串可以取代 n1,n2 之间的行!
  d 删除匹配的内容
  i 插入匹配的内容,i的后面可以接字串,而这些字串会在新的一行出现(目前的上一行)
  p 打印匹配的内容,即将某个选择的数据印出
  s 取代匹配的内容,可以直接进行取代的工作

Eg:
#打印输出内容的第一行
[root@localhost ~]# cat -n /etc/passwd | sed -n '1p'
     1  root:x:0:0:root:/root:/bin/bash
[root@localhost ~]#

#查找符合条件的字符串,类似grep
[root@localhost ~]# ifconfig ens160 | sed -n '/netmask/p'
        inet 10.10.120.100  netmask 255.255.255.0  broadcast 10.10.120.255
[root@localhost ~]# 
[root@localhost ~]# ifconfig ens160 | grep netmask 
        inet 10.10.120.100  netmask 255.255.255.0  broadcast 10.10.120.255
[root@localhost ~]# 

#替换文件中的内容
[root@localhost ~]# cat 1.txt 
112233
[root@localhost ~]# sed -i "s/1122/123/g" 1.txt           
[root@localhost ~]# cat 1.txt                   
12333
[root@localhost ~]#
2.3 awk

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

Usage: awk [POSIX or GNU style options] -f progfile [--] file ...
  or:  awk [POSIX or GNU style options] [--] 'program' file ...

#常用功能——通过print功能将字段数据列出来
[root@localhost ~]# last -n 5
root     pts/1        10.10.120.1      Wed Feb 21 20:15   still logged in
root     tty1                          Wed Feb 21 01:13    gone - no logout
root     pts/0        10.10.120.1      Tue Feb 20 21:18 - 21:38 (1+00:19)
root     pts/0        10.10.120.1      Tue Feb 20 13:40 - 14:50  (01:10)
root     pts/0        10.10.120.1      Tue Feb 20 11:43 - 13:36  (01:52)

wtmp begins Tue Feb 20 07:51:28 2024
[root@localhost ~]# last -n 5 | awk '{printf $1 "\t" $3 "\n"}'
root    10.10.120.1
root    Wed
root    10.10.120.1
root    10.10.120.1
root    10.10.120.1

wtmp    Tue
[root@localhost ~]#

3 文件格式化处理

3.1 格式化打印-printf

printf命令模仿了C程序库里的printf()程序,功能和echo类似

语法: printf [-v var] format [arguments]

选项和参数:
  \a    警告声音输出
  \b    退格键(backspace)
  \f    清除屏幕(form feed)
  \n    输出新的一行
  \r    回车按键
  \t    水平的[tab]按键
  \v    垂直的[tab]按键
3.2 文本对比工具-diff

以逐行的方式,比较文本文件的异同处

#文件完全一样时没有反馈
[root@localhost ~]# cat 2.txt > 3.txt
[root@localhost ~]# diff 2.txt 3.txt
[root@localhost ~]# 
#文件不同时会反会不同的部分
[root@localhost ~]# echo 1234 >> 2.txt 
[root@localhost ~]# echo 4321 >> 3.txt      
[root@localhost ~]# diff 2.txt 3.txt 
8c8
< 1234
---
> 4321
[root@localhost ~]#

4 文件查找

4.1 locate

查找符合条件的文档,他会去保存文档和目录名称的数据库内,查找合乎范本样式条件的文档或目录。一般输入locate [filename]来查找文件

Usage: locate [OPTION]... [PATTERN]...

Options:
  -i   忽略大小写的差异
  -c   不输出文件名,仅计算找到的文件数量
  -l n 仅输出n行
  -S   输出locate所使用的数据库文件的相关信息
  -r   后面可接正则表达式的显示方式

Eg:
#列出5个和passwd相关的文件名
[root@localhost ~]# locate -l 5 passwd
/etc/passwd
/etc/passwd-
/etc/pam.d/passwd
/etc/security/opasswd
/usr/bin/gpasswd
[root@localhost ~]#
4.2 find

在指定的目录下寻找文件或目录。可以添加不同的参数来过滤查找的结果

Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]

Options:
  -name                    按文件名查找
  -type                    按文件类型查找
  -size [+-]size[cwbkMG]   按文件大小查找
  -mtime                   按修改时间查找
  -user                    按文件所有者查找
  -group                   按文件所属组查找

Eg:
#查找/etc目录下所有扩展名为sh的文件:
[root@localhost ~]# find /etc/ -name *.sh -type f   
/etc/bash_completion.d/authselect-completion.sh
/etc/profile.d/lang.sh
/etc/profile.d/colorgrep.sh
/etc/profile.d/colorxzgrep.sh
/etc/profile.d/colorls.sh
/etc/profile.d/less.sh
/etc/profile.d/gawk.sh
/etc/profile.d/colorzgrep.sh
/etc/profile.d/which2.sh
/etc/profile.d/vim.sh
/etc/profile.d/bash_completion.sh
/etc/X11/xinit/xinitrc.d/50-systemd-user.sh
/etc/dhcp/dhclient.d/chrony.sh
/etc/smartmontools/smartd_warning.sh
[root@localhost ~]#

叁 · Linux文件系统

1 Linux磁盘分区表

1.1 MBR

在早期,linux系统为了兼容Windows的磁盘,使用了支持Windows的MBR(Master Boot Record,主引导记录)的方式来处理启动引导和分区表。

MBR结构的分区,第一个扇区大小是512字节(旧的磁盘扇区都是512字节),包含最多446字节的启动代码、4个硬盘分区表项(每个表项16字节,共64字节)、2个签名字节(0x55,0xAA)。

MBR分区有以下特点:

  • 支持的硬盘最大容量是2TB(超出部分无法被识别)
  • 最多有4个主分区或3个主分区、一个扩展分区
1.2 GTP

GPT分区模式使用GUID分区表,是源自EFI标准的一种较新的磁盘分区表结构的标准。与普遍使用的主引导记录(MBR)分区方案相比,GPT提供了更加灵活的磁盘分区机制。

GTP分区有以下优点:

  • 支持容量在2TB以上的硬盘
  • 每个磁盘的分区个数几乎没有限制(Windows仅支持128个分区)
  • 分区大小几乎没有限制(GPT分区提供了64位来记录开始/结束的扇区号)

2 Linux磁盘管理

2.1 lsblk

lsblk命令是"list block"的缩写,用于列出所有系统识别到的可用块设备的信息(不包括RAM)

Usage:
 lsblk [options] [<device> ...]

Options:
 -a, --all            打印所有设备
 -b, --bytes          以字节为单位显示分区大小
 -d, --nodeps         不打印从属或持有者
 -z, --zoned          print zone model
 -e, --exclude <list> exclude devices by major number (default: RAM disks)
 -f, --fs             输出有关文件系统的信息
 -i, --ascii          仅使用ASCII字符
 -I, --include <list> 仅显示有指定主要编号的设备
 -n, --noheadings     不打印标题行
 -S, --scsi           输出有关SCSI设备的信息
 -t, --topology       输出有关拓扑的信息

Eg:
[root@localhost ~]# lsblk
NAME        MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
sr0          11:0    1 1024M  0 rom  
nvme0n1     259:0    0   20G  0 disk 
├─nvme0n1p1 259:1    0    1G  0 part /boot
└─nvme0n1p2 259:2    0   19G  0 part 
  ├─rl-root 253:0    0   17G  0 lvm  /
  └─rl-swap 253:1    0    2G  0 lvm  [SWAP]
[root@localhost ~]# 
2.2 fdisk

该命令用于创建和维护分区表的程序,兼容 DOS 类型的分区表、BSD 或者 SUN 类型的磁盘列表 

Usage:
 fdisk [options] <disk>      change partition table
 fdisk [options] -l [<disk>] list partition table(s)

 选择指定磁盘开始磁盘分区

[root@localhost ~]# fdisk /dev/sda

Welcome to fdisk (util-linux 2.32.1).
Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.

Device does not contain a recognized partition table.
Created a new DOS disklabel with disk identifier 0x7e8ba37e.

Command (m for help): 

常用功能:

Command (m for help): m

Help:

  DOS (MBR)
   a   活动分区标记/引导分区

  Generic
   d   删除分区
   l   显示分区类型
   n   新建分区
   p   显示分区信息
   t   设置分区号
   v   新建分区

  Misc
   m   显示菜单和帮助信息

  Save & Exit
   w   保存并推出
   q   不保存退出


Command (m for help): 

 建立磁盘分区

Command (m for help): n    #创建一个1G的主分区
Partition type
   p   primary (0 primary, 0 extended, 4 free)
   e   extended (container for logical partitions)
Select (default p): p
Partition number (1-4, default 1): 
First sector (2048-10485759, default 2048): 
Last sector, +sectors or +size{K,M,G,T,P} (2048-10485759, default 10485759): +1G

Created a new partition 1 of type 'Linux' and of size 1 GiB.

Command (m for help): n    #创建一个2G的主分区
Partition type
   p   primary (1 primary, 0 extended, 3 free)
   e   extended (container for logical partitions)
Select (default p): p
Partition number (2-4, default 2): 
First sector (2099200-10485759, default 2099200): 
Last sector, +sectors or +size{K,M,G,T,P} (2099200-10485759, default 10485759): +2G                              

Created a new partition 2 of type 'Linux' and of size 2 GiB.

Command (m for help): n    #将剩余空间划分给扩展分区
Partition type
   p   primary (2 primary, 0 extended, 2 free)
   e   extended (container for logical partitions)
Select (default p): e
Partition number (3,4, default 3): 
First sector (6293504-10485759, default 6293504): 
Last sector, +sectors or +size{K,M,G,T,P} (6293504-10485759, default 10485759): 

Created a new partition 3 of type 'Extended' and of size 2 GiB.

Command (m for help): n    #将扩展分区划分为一个逻辑分区
All space for primary partitions is in use.
Adding logical partition 5
First sector (6295552-10485759, default 6295552): 
Last sector, +sectors or +size{K,M,G,T,P} (6295552-10485759, default 10485759): 

Created a new partition 5 of type 'Linux' and of size 2 GiB.

Command (m for help): 

 保存

Command (m for help): w
The partition table has been altered.
Calling ioctl() to re-read partition table.
Syncing disks.

[root@localhost ~]# lsblk
NAME        MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
sda           8:0    0    5G  0 disk 
├─sda1        8:1    0    1G  0 part 
├─sda2        8:2    0    2G  0 part 
├─sda3        8:3    0    1K  0 part 
└─sda5        8:5    0    2G  0 part 
sr0          11:0    1 1024M  0 rom  
nvme0n1     259:0    0   20G  0 disk 
├─nvme0n1p1 259:1    0    1G  0 part /boot
└─nvme0n1p2 259:2    0   19G  0 part 
  ├─rl-root 253:0    0   17G  0 lvm  /
  └─rl-swap 253:1    0    2G  0 lvm  [SWAP]
[root@localhost ~]# 
2.3 格式化
  1. mkfs.ext2/3/4        将磁盘格式化为ext2/3/4文件系统
  2. mkfs.fat                 将磁盘格式化为fat文件系统
  3. mkfs.xfs                将磁盘格式化为xfs文件系统
  4. mkswap                将磁盘格式化为交换分区
#以ext4为例
[root@localhost ~]# mkfs.ext4 /dev/sda1 
mke2fs 1.45.6 (20-Mar-2020)
Creating filesystem with 262144 4k blocks and 65536 inodes
Filesystem UUID: 0f9eeb23-f3ad-47fc-b160-5c842bb23d2b
Superblock backups stored on blocks: 
        32768, 98304, 163840, 229376

Allocating group tables: done                            
Writing inode tables: done                            
Creating journal (8192 blocks): done
Writing superblocks and filesystem accounting information: done

[root@localhost ~]# mkswap /dev/sda2 
Setting up swapspace version 1, size = 2 GiB (2147479552 bytes)
no label, UUID=724edf7f-378f-4557-a2a7-d1869d09b888
[root@localhost ~]# 
2.4 mount

用于挂载Linux系统外的文件

Usage: mount [-a] 分区 挂载点

Eg:
[root@localhost ~]# mount /dev/sda1 /data1/        
[root@localhost ~]# df
Filesystem          1K-blocks    Used Available Use% Mounted on
devtmpfs               893976       0    893976   0% /dev
tmpfs                  914100       0    914100   0% /dev/shm
tmpfs                  914100    8932    905168   1% /run
tmpfs                  914100       0    914100   0% /sys/fs/cgroup
/dev/mapper/rl-root  17811456 2118068  15693388  12% /
/dev/nvme0n1p1        1038336  216296    822040  21% /boot
tmpfs                  182820       0    182820   0% /run/user/0
/dev/sda1              999320    2564    927944   1% /data1
[root@localhost ~]# 
2.5 umount

卸除目前挂在Linux目录中的文件系统

Usage: umount 挂载点

Eg:
[root@localhost ~]# umount /data1 
[root@localhost ~]# df
Filesystem          1K-blocks    Used Available Use% Mounted on
devtmpfs               893976       0    893976   0% /dev
tmpfs                  914100       0    914100   0% /dev/shm
tmpfs                  914100    8932    905168   1% /run
tmpfs                  914100       0    914100   0% /sys/fs/cgroup
/dev/mapper/rl-root  17811456 2118048  15693408  12% /
/dev/nvme0n1p1        1038336  216296    822040  21% /boot
tmpfs                  182820       0    182820   0% /run/user/0
[root@localhost ~]# 
2.6 swapon

Linux系统的内存管理必须通过交换区来建立虚拟内存,这条命令用于开启或查看交换分区

Usage: swapon [options] [<spec>]

Options:
 -a, --all                启用/etc/fstab中的所有交换分区
 -p, --priority <prio>    指定交换设备的优先级
 -s, --summary            显示有关已用交换设备的摘要

Eg:
[root@localhost ~]# swapon
NAME      TYPE      SIZE USED PRIO
/dev/dm-1 partition   2G   0B   -2
[root@localhost ~]# swapon /dev/sda2 
[root@localhost ~]# swapon 
NAME      TYPE      SIZE USED PRIO
/dev/dm-1 partition   2G   0B   -2
/dev/sda2 partition   2G   0B   -3
[root@localhost ~]# 
2.8 swapoff

有开启自然就会有关闭嘛

Usage:
 swapoff [options] [<spec>]

Options:
 -a, --all     将/etc/fstab文件中所有设置为swap的设备关闭

Eg:
[root@localhost ~]# swapoff /dev/sda2
[root@localhost ~]# swapon
NAME      TYPE      SIZE USED PRIO
/dev/dm-1 partition   2G   0B   -2
[root@localhost ~]# 

肆 · 初识Shell

1 认识shell

1.1 什么是shell

shell既是一种应用程序,又是一种程序设计语言。我们常说的shell一般是指shell语言

shell作为一种程序时通常是指用户和操作系统内核之间的交互界面。在这个界面下,用户可以通过命令行输入命令,执行各种操作,如启动程序、管理文件、进行系统设置等。

1.2 shell脚本

shell脚本,也就是shell script,是一种为shell编写的脚本程序。它是由一系列命令组成的文本文件。这些命令按顺序执行,可以用来自动化执行一系列的操作,节省用户的时间。

2 shell变量

2.1 变量的命名要求
  1. 区分大小写
  2. 不能使用程序中保留的字和变量,如if,for
  3. 只能使用数字、字符以及下划线,且不能以数字开头
2.2 变量的使用与设置
2.2.1 变量的分类
  • 普通变量:生效范围为当前shell进程
  • 环境变量:生效范围为当前shell进程及其子进程
  • 本地变量:生效范围为当前shell进程中的某段代码,通常指函数
2.2.2 变量的使用

在变量名前加上$或者以${变量}的方式都可以使用变量,但我比较喜欢第二种

  • #变量的使用(echo):
    [root@localhost ~]# echo $PATH
    /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
    [root@localhost ~]# echo ${PATH}
    /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
    [root@localhost ~]#
    
    #在变量名前加上$或者${变量}使用变量的区别
    [root@localhost ~]# echo $PATH123  
    
    [root@localhost ~]# echo ${PATH}123
    /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin123
    [root@localhost ~]# 
2.2.3 变量的赋值
  • 变量设置的规则
    • 变量和变量的值以一个封号链接
      name=Root
    • 等号两边不能直接接空格
      #错误示范
      name = Root
      name=dzzx my
    • 变量的值若有空格可使用双引号或单引号将内容连起来
      [root@localhost ~]# echo $name
      
      [root@localhost ~]# name="dzzx my"
      [root@localhost ~]# echo $name    
      dzzx my
      [root@localhost ~]#
  • 双引号内的变量会被替换为变量的值
    [root@localhost ~]# echo $var
    
    [root@localhost ~]# var="lang is $LANG"  
    [root@localhost ~]# echo $var
    lang is en_US.UTF-8
    [root@localhost ~]# 
  • 单引号中的变量不会被替换为变量的值
    [root@localhost ~]# var='lang is $LANG'
    [root@localhost ~]# echo $var           
    lang is $LANG
    [root@localhost ~]# 
  • 取消变量:unset 变量名
    [root@localhost ~]# unset var
    [root@localhost ~]# echo $var
    
    [root@localhost ~]# 

3 编写脚本

3.1 shell脚本创建过程

第一步:使用文本编辑器创建文件

第二步:在开头指定脚本解释器

#!/bin/bash

第三步:给文件加上可执行的权限

第四步:运行脚本

3.2 第一个shell脚本

不想用经典的hello world了

[root@localhost ~]# cat 1.sh 
#!/bin/bash
echo "Quick brown fox jumps over the lazy dog 1234567890"
[root@localhost ~]# sh 1.sh 
Quick brown fox jumps over the lazy dog 1234567890
[root@localhost ~]# 
3.3 用shell解鸡兔同笼
3.3.1 read

read命令用于从标准输入读取数值

Usage: read [-ers] [-a array] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name ...]

Eg:
#获取变量Heads的值,并显示提示文本
[root@localhost ~]# read -p "How many heads?" Heads
How many heads?30
[root@localhost ~]# echo $Heads
30
[root@localhost ~]# 
3.3.2 解题

题目:今有鸡与兔同在一个笼子里,已知头有30,腿有80,问鸡与兔各有多少只?

脚本:

#!/bin/bash
read -p "How many heads?" Heads
read -p "How many foot?" Foot
Rabbit=$(((${Foot} - 2 * ${Heads})/2))
Chicken=$((${Heads}-${Rabbit}))
echo "There are ${Chicken} chickens and ${Rabbit} rabbits !"

答案:

[root@localhost ~]# . 2.sh   
How many heads?30
How many foot?80
There are 20 chickens and 10 rabbits !
[root@localhost ~]# 
3.4 用shell脚本批量创建用户
3.4.1 for的语法
for 变量 in {范围}
do
    条件
done

Eg:
for i in {1..4}
do
    echo $i
done
3.4.2 if的语法
if [ command ]
then
     语句
elif [ command ]
then
     语句
else
     语句
fi
3.4.3 创建100个用户

脚本:

#!/bin/bash
for i in {001..100}
do
        username=user$i
        if id -u ${username} >/dev/null 2>&1
        then
                echo useradd: user \'${username}\' already exists
        else
                useradd ${username}
                echo useradd: user \'${username}\' was successfully created
        fi
done

 效果:

[root@localhost ~]# . 3.sh   
useradd: user 'user01' already exists
useradd: user 'user02' already exists
useradd: user 'user03' already exists
useradd: user 'user04' already exists
......
  • 16
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值