shell脚本概念
作为计算机语言来理解可以认为它是操作系统的外壳。 可以通过shell 命令来操作和控制操作系统,比如 Linux中的shell命令就包括 ls、cd、pwd 等等。
shell 在内核的基础上编写的一个应用程序,它连接了用户和 Linux 内 核,从而让用户能够更加便捷、高效、安全的使用 linux 内核,这其实 就是 shell 的本质。
Shell 其实是一个命令解释器,它通过接 受用户输入的 Shell 命令来启动、暂停、停止程序的运行或对计算机进 行控制。
shell脚本注意事项
shell命名: shell脚本名称命名一般为英文、大写、小写、后缀以.sh结尾
不能使用特殊符号、空格
名称要写的一眼可以看出功能,也就是顾名思义
shell脚本首行需要#!/bin/bash开头
shell脚本变量不能以数字、特殊符号开头,可以使用下划线 _,但不能 用破折号——
编写shell脚本
[root@shell ~]# vim hello.sh
#!/bin/bash echo "Hello World!" # 输出“Hello World!”
[root@shell ~]# bash hello.sh //执行
[root@shell ~]# sh hello.sh
shell脚本自动化安装nginx
[root@shell ~]# mkdir /root/shell
[root@shell ~]# vim /root/shell/install_nginx.sh
#!/bin/bash
yum -y install gcc gcc-cc+ make pcre_devel openssl-devel wget cd /usr/local/src/
wget ' https://nginx.org/download/nginx-1.22.1.tar.gz'
tar xf nginx-1.22.1.tar.gz
cd nginx-1.22.1
./configure --prefix=/usr/local/nginx
make -j 4
make install
[root@shell ~]# sh /root/shell/install_nginx.sh
变量
[root@shell ~]# set a=3
[root@shell ~]# echo a
a
[root@shell ~]# unset a //清除变量
环境变量
$PWD //查看当前目录
$SHELL
$USER
查看环境位置变量:[root@shell ~]# env
输出1-5
[root@shell ~]# vim tset001.sh
#!/bin/bash
echo $1
echo $2
echo $3
echo $4
echo $5
[root@shell ~]# bash tset001.sh 1 2 3 4 5
shell脚本创建用户
[root@shell ~]# vim creat
#!/bin/bash
useradd $1
echo $2|passwd --stdin $1
[root@shell ~]# bash creat zzzz zzzz //用户+密码
Changing password for user zzzz.
passwd: all authentication tokens updated successfully.
数字比较大小
[root@shell ~]# vim if.sh
#!/bin/bash
if [ $1 -eq $2 ]; then
echo "两数相等"
else
echo"两数不相等"
fi
[root@shell ~]# bash if.sh 3 5
if.sh: line 5: echo两数不相等
其他练习
[root@shell ~]# aaa="abc"
[root@shell ~]# echo $aaa
abc
[root@shell ~]# test $aaa == "abc"
[root@shell ~]# echo $?
0
[root@shell ~]# test $aaa == "aaa"
[root@shell ~]# echo $?
1
进行对文件的编辑
if语句
[root@shell ~]# vim menu.sh
#!/bin/bash
echo "1新增文件 2删除文件 3查找文件 4修改文件"
read -p "输入选项:"
if [ $m == 1 ];then
touch aaaa.txt
elif [ $m == 2 ];then
rm -rf aaaaa.txt
else
echo "不能执行"
fi
[root@shell ~]# sh menu.sh
1新增文件 2删除文件 3查找文件 4修改文件
输入选项:2
for循环
格式
for 变量名 in 取值列表(范围)
do
命令序列
done
分隔值循环
[ root@localhost test]# vim quzhi.sh
for home in 北京 上海 ⼴州 深圳
do
echo "$home 是个好地⽅!"
done
[root@localhost test]# bash quzhi.sh
北京 是个好地⽅!
上海 是个好地⽅!
⼴州 是个好地⽅!
深圳 是个好地⽅!
[root@localhost test]#
在命令结果中循环
[root@localhost test]# vim 1.sh
#!/bin/bash
x=1
for user in $(awk -F':' '{print $1}' /etc/passwd)
do
echo "第 $x ⽤户名称为: $user"
let x=x+1
done
echo "该系统有 $(($x-1)) 个⽤户"
[root@localhost test]# bash 1.sh
第 1 ⽤户名称为: root
...省略部分内容
第 45 ⽤户名称为: yunjisuan
第 46 ⽤户名称为: apache
第 47 ⽤户名称为: nginx
该系统有 47 个⽤户
[root@localhost test]#
while 循环
while 条件测试操作
do
命令序列
done
while 和 for区别
while循环也有条件判断,当条件成立的时候,会循环执行。当条件不成立退出
if判断当条件成立时,会执行一次,然后退出。当条件不成立时直接退出
批量添加用户
shell脚本读取用户输入和计算
[root@shell ~]# read -p "输入数据" s //-p:有提示信息
输入数据ghjghhjghj //有回显
[root@shell ~]# echo $s
ghjghhjghj
[root@shell ~]# read -p "输入数据" -s s
输入数据[root@shell ~]# echo $s //无回显
ddddd
更改网卡设置
[root@shell ~]# vim initserver.sh