前言:本博客仅作记录学习使用,部分图片出自网络,如有侵犯您的权益,请联系删除
1、test语句
1.1、test语句格式
test 条件
条件为真返回 0,条件为假返回 1
[ 条件 ]
1.2、test 能够理解3种类型的表达式
字符串 | 数字 | 文件 | |||
---|---|---|---|---|---|
-n string | 字符串长度不为零 | eq | 等于 | -f | 存在且是普通文件 |
-z string | 字符串长度为0 | ne | 不等于 | -d | 存在且是目录 |
= | 判断两个字符串是否一样 | ge | 大于 | -h | 存在且是符号链接 |
!= | 判断两个字符串是否不一样 | le | 小于等于 | -b | 块设备 |
gt | 大于 | -c | 字符设备 | ||
lt | 小于 | -e | 文件存在 |
2、if条件判断语句
2.1、常用的单/双分支
If条件判断语句,通常以if开头,fi结尾。也可加入else或者elif进行多条件的判断
# 单分支语句 ---比较大小
if (条件表达式);then
语句1
fi
# 双分支if 语句
if (表达式)
语句1
else
语句2
fi
# 多支条件语句 ---判断成绩
if (表达式)
语句1
elif
语句2
elif
语句2
fi
2.2、if 常见判断逻辑运算符详解
运算符 | 作用 |
---|---|
-f | 判断文件是否存在 eg: if [ -f filename ]; |
-d | 判断目录是否存在 eg: if [ -d dir ]; |
-eq(equal) | 等于,应用于整型比较 equal; |
-ne(not equal) | 不等于,应用于整型比较 not equal; |
-lt(less than) | 小于,应用于整型比较 letter; |
-gt(greater than) | 大于,应用于整型比较 greater; |
-le(less than or equal to) | 小于或等于,应用于整型比较; |
-ge(greater than or equal to) | 大于或等于,应用于整型比较; |
-a | 双方都成立(and) 逻辑表达式 –a 逻辑表达式; |
-o | 单方成立(or) 逻辑表达式 –o 逻辑表达式; |
-z | 空字符串 |
-x | 是否具有可执行权限 |
|| | 单方成立; |
&& | 双方都成立表达式 |
2.3、简单实例:
(1)输入号码判断正确
#!/bin/bash
read -p "请输入号码: " num
if [ $num = 1 ];then
echo "1"
elif [ $num = 2 ];then
echo "2"
else
echo "输入有误!"
fi
(2)脚本if.sh,必须在脚本后加上适当的参数脚本才能正确执行
#!/bin/bash
if [ "$1" = "hello" ]; then
echo "Hello! How are you ?"
elif [ "$1" = "" +]; then
echo "You MUST input parameters"
else
echo "The only accept parameter is hello"
fi
(3)检测apache是否运行,如果没有运行则启动,并记录启动的时间,保存到日志中
#!/bin/bash
# 获取Apache服务状态
status=$(systemctl status httpd | grep Active | awk '{print $2}')
# 检查Apache服务是否正在运行
if [ "$status" == "active" ]; then
echo "apache is running"
else
# 确保安装Apache
yum install -y httpd
# 启动Apache服务,并记录启动时间
systemctl start httpd && echo "$(date) - apache is started" >> /root/apache_start.log
echo "apache is started"
fi
(4)测试ip地址主机位从2到100的机器是否存活,并把存活的机器记录到文本文件alivehost.txt内。(使用
ping命令)
#!/bin/bash
# 定义基础IP地址
base_ip="192.168.1"
# 定义网络掩码
netmask=".255.255.0"
# 定义存活主机记录文件
alive_file="alivehost.txt"
# 清空或创建存活主机记录文件
> "$alive_file"
# 遍历主机位从2到100
for i in {2..100}; do
# 构造完整的IP地址
ip_to_test="${base_ip}.${i}${netmask}"
# 使用ping命令测试主机,超时设置为1秒,只发送一个数据包
if ping -c 1 -W 1 "$ip_to_test" &> /dev/null; then
# 如果ping成功,将IP地址写入alivehost.txt文件
echo "$ip_to_test is alive" >> "$alive_file"
fi
done
echo "存活的主机已经记录到 $alive_file"
3、for循环语句
3.1、for循环语句格式
格式:for name [ [ in [ word ... ] ] ; ] do list ; done
for 变量名 in 取值列表; do
语句 1
done
3.2、简单示例:
(1)测试成产环境的主机存活性
#!/usr/bin/env bash #
# Author:
>ip_alive.txt
>ip_down.txt
segment="192.168.161"
for i in {2..254}
do
{
ping -c1 $segment.$i &>/dev/null
if [ $? -eq 0 ];then
printf "alive: $segment.$i\n" >>ip_alive.txt
else
printf "down: $segment.$i\n" >>ip_down.txt
fi
}&
done
wait
echo "finish..."
(2)for循环批量创建用户
#!/bin/bash
while :
do
read -p "请设置用户前缀/数量/密码: " prefix num pass
cat <<-EOF
用户前缀:$prefix
用户数量:$num
用户密码:$pass
EOF
read -p "是否确认创建:[Y/N]" action
if [ $action = y ];then
break
fi
done
echo "starting create users..."
for i in `seq -w $num`
do
user=$prefix$i
id $user &>/dev/null
if [ $? -eq 0 ];then
echo "$user is already exist"
else
useradd $user
echo $pass | passwd --stdin $user &>/dev/null
fi
done
4、while循环语句
4.1、while语句格式
While循环语句与for循环功能类似,主要用于对某个数据域进行循环读取、对文件进行遍历,通常用于需要循环某个文件或者列表,满足循环条件会一直循环,不满足则退出循环,其语法格式以while…do开头,done结尾与while 关联的还有一个 until 语句,它与 while 不同之处在于,是当条件表达式为 false 时才循环,实际使用中比较少
while (表达式)
do
语句1
done
4.2、 break 和 continue 语句
- break 是终止循环
-
continue 是跳出当前循环
4.3、简单示例
(1) 命令行输入一个参数 n,计算 1+2+..+n 的值;
#!/bin/bash
sum=0
i=0
while [ $i -le $1 ]; do # 只要第i个数小于我们输入的参数,就执行循环
sum=$((sum + i)) # 使用算术扩展来更新sum的值
i=$((i + 1)) # i自增
done
echo "SUM=$sum"
5、case语句
5.1、case语句格式
Case选择语句,主要用于对多个选择条件进行匹配输出,与if elif语句结构类似,通常用于脚本传递输入参数,打印出输出结果及内容,其语法格式以Case…in开头,esac结尾。语法格式如下:
case 模式名 in
模式 1)
命令
;;
模式 2)
命令
;;
*)
不符合以上模式执行的命令
esac
# 每个模式必须以右括号结束,命令结尾以双分号结束。
5.2、简单示例:
(1)建立脚本case.sh,当执行时,要求我们在键盘输入适当的值(one|two|three),当输入正确时并打印,当输入错误时会提示你,应该输入正确的值
#!/bin/bash
# 提示用户输入
read -p "请输入适当的值 (one|two|three): " input
# 使用 case 语句来判断输入
case $input in
one)
echo "输入正确: one"
;;
two)
echo "输入正确: two"
;;
three)
echo "输入正确: three"
;;
*)
echo "输入错误: 请输入 one、two 或 three 中的一个。"
;;
esac
(2)判断用户输入的是否是数字
read -p "请输入:" get
case $get in
[0-9][0-9]*) #判断输入是否是数字
echo -e "你输入是数字。\n"
;;
*)
echo -e "你输入的不是数字。\n"
;;
esac
6、select 选择语句
6.1、select
select 是一个类似于 for 循环的语句
Select语句一般用于选择,常用于选择菜单的创建,可以配合PS3来做打印菜单的输出信息,其语法格式以select…in do开头,done结尾
select i in (表达式)
do
语句
done
7、until语句
7.1、until语句结构
until 条件
do
循环体
done
7.2、示例
# cat until.sh
#!/bin/bash
# until 循环和 while 循环。这两个循环都用于从变量 x 的初始值 1 开始计数,直到 x 的值达到或超过 10 时停止
x=1
until [ $x -ge 10 ]
do
echo $x
x=`expr $x + 1`
done
x=1
while [ ! $x -ge 10 ]
do
echo $x
x=`expr $x + 1`
done
8、shell循环控制shift、continue、break、exit
8.1、shift命令
位置参数可以用shift命令左移。比如shift 3表示原来的$4现在变成$1,原来的$5现在变成$2等等,原来 的$1、$2、$3丢 弃,$0不移动。不带参数的shift命令相当于shift 1 对于位置变量或命令行参数,其个数必须是确定的,或者当 Shell 程序不知道其个数时,可以把所有参数一 起赋值给变量 $*。 若用户要求 Shell 在不知道位置变量个数的情况下,还能逐个的把参数一一处理,也就是在 $1 后为 $2, 在 $2 后面为 $3 等,则需要用shift把所有参数变成$1
示例:
#测试 shift 命令(x_shift3.sh)
[root@newrain shell]# cat x_shift3.sh
#!/bin/bash
shift
echo "第一个位置参数: $1"
[root@newrain shell]# bash x_shift3.sh 2 3
第一个位置参数: 3
# 测试shift命令(x_shift.sh)
[root@centos ~]# cat x_shift.sh
#!/bin/bash
until [ $# -eq 0 ]
do
echo "第一个参数为:$1 参数个数为:$#"
shift
done
[root@centos ~]# bash x_shift.sh 1 2 3 4
第一个参数为:1 参数个数为:4
第一个参数为:2 参数个数为:3
第一个参数为:3 参数个数为:2
第一个参数为:4 参数个数为:1
可知 shift 命令每执行一次,变量的个数($#)减一,而变量值提前一位
# 用 until 和 shift 命令计算所有命令行参数的和
[root@centos ~]# cat s_shift2.sh
#!/bin/bash
sum=0
until [ $# -eq 0 ]
do
sum=`expr $sum + $1`
shift
done
echo "sum is: $sum"
[root@centos ~]# bash s_shift2.sh 10 20 15
sum is: 45
8.2、continue、break、exit命令
- break:结束并退出本次循环
- continue:在循环中不执行continue下面的代码,转而进入下一轮循环
- exit:退出脚本,常带一个整数给系统,如exit 0
可理解为:break是立马跳出循环;continue是跳出当前条件循环,继续下一轮条件循环;exit是直接退出整个脚本
例如:在循环过程中,有时候需要在未达到循环结束条件时强制跳出循环,Shell使用两个命令来实现该功能:break和continue。break终止后面的所有循环
示例:
# 脚本进入死循环直至用户输入数字大于5
[root@centos ~]# cat test.sh
#!/bin/bash
while :
do
echo -n "input a number between 1 to 5:"
read aNum
case $aNum in
1|2|3|4|5)
echo "Your number is $aNum!"
;;
*)
echo "you do not select a number between 1 to 5!"
;;
esac
done
# 但是此脚本不会停止,此时用到break与exit
#!/bin/bash
while true
do
read -p "请输入[1/2]" num1
case $num1 in
1)
echo $num1
;;
2)
while true
do
read -p "再次输入[1/2]:" num2
case $num2 in
1) echo $num2;;
2) break; #将此处换成exit,再次尝试
esac
done
esac
done
致谢
在此,我要对所有为知识共享做出贡献的个人和机构表示最深切的感谢。同时也感谢每一位花时间阅读这篇文章的读者,如果文章中有任何错误,欢迎留言指正。
学习永无止境,让我们共同进步!!