shell编程规范与变量
shell脚本概述
1-1shell脚本的概念
1、将要执行的命令按照顺序保存到一个文本文件
2、给该文件可执行的权限,便于运行 +一个x的执行权限
3、可结合各种shell控制语句以完成更复杂的操作
1-2shell脚本应用场景
1、重复性操作
2、批量化事务处理
3、自动化运维管理
4、服务器运行状态监控
5、定时任务执行
shell的作用
1-1shell作用
位于系统内核与用户之间,解释翻译命令
1-2 用户登录shell
1-1登陆后默认使用的shell程序,一般为/bin/bash
1-2不同shell的内部命令、运行环境等会有所区别
[root@localhost ~]# cat /etc/shells
/bin/sh
‘/bin/bash’
/sbin/nologin
/usr/bin/sh
/usr/bin/bash
/usr/sbin/nologin
/bin/tcsh
/bin/csh
写一个shell脚本
1-1编写脚本代码
使用vi编辑器然后按照顺序依次编写Linux命令,且每行只有一条
[root@localhost ~]# vi frist.sh
#!/bin/bash ‘shell脚本固有格式’
cd /boot/
pwd
ls -lh vml*
[root@localhost ~]# chmod 744 frist.sh
[root@localhost ~]# ./frist.sh
/boot
-rwxr-xr-x. 1 root root 5.7M 10月 23 13:40 vmlinuz-0-rescue-33c124456fa34c50a98483245dfea58d
-rwxr-xr-x. 1 root root 5.7M 8月 23 2017 vmlinuz-3.10.0-693.el7.x86_64
当一句话结束时,使用分号同时使用两条命令
[root@localhost boot]# ls;who ‘命令用分号隔开可以同时执行两个命令’
config-3.10.0-693.el7.x86_64
efi
grub
grub2
initramfs-0-rescue-33c124456fa34c50a98483245dfea58d.img
initramfs-3.10.0-693.el7.x86_64.img
initrd-plymouth.img
symvers-3.10.0-693.el7.x86_64.gz
System.map-3.10.0-693.el7.x86_64
vmlinuz-0-rescue-33c124456fa34c50a98483245dfea58d
vmlinuz-3.10.0-693.el7.x86_64
root :0 2020-11-1 13:43 (:0)
root pts/0 2020-11-1 17:06 (:0)
管道与重定向操作
交互式硬件设备
标准输入:从该设备接受用户输入的数据
标准输出:通过该设备向用户输出数据
标准错误:通过该设备报告执行出错信息
重定向操作
试列如下
[root@localhost ~]# chattr +i /etc/passwd ‘给账号文件加锁’
[root@localhost ~]# lsattr /etc/passwd ‘查看已枷锁’
----i----------- /etc/passwd
[root@localhost ~]# useradd zhaoyun ‘测试’
useradd:无法打开 /etc/passwd ‘标准错误输出’
[root@localhost ~]# useradd zhaoyun 2> err.txt ‘使用2>重定向’
[root@localhost ~]# ls
anaconda-ks.cfg frist.sh test.sh 模板 图片 下载 桌面
err.txt initial-setup-ks.cfg 公共 视频 文档 音乐
[root@localhost ~]# cat err.txt ‘查看’
useradd:无法打开 /etc/passwd
管道操作符号“|”
将左侧的命令输出结果,作为右侧命令的处理对象
'cmd1 | cmd2 [… | cmdn]
[root@localhost ~]# grep “bashKaTeX parse error: Expected 'EOF', got '#' at position 105: …ot@localhost ~]#̲ grep "bash” /etc/passwd | awk -F: ‘{print $1,$7}’
root /bin/bash
gsy /bin/bash
[root@localhost ~]#
正则表达式
grep egrep 过滤关键字
sed 按行读取
awk 按列读取数据
awk -F 指定分隔符 如果不加-F,则默认分隔符为制表符或空格
‘{print 打印 $1 第一个参数 $7 第七个参数}’
$1 $2 代表位置变量