for循环语句
-
案例1,循环输出
#!/bin/bash #Use: for循环 测试1 #Author: wl_it #Date: 2020.05.08 # seq 1 15 表示输出1到15的数字 for i in `seq 1 15` do echo -e "\033[32m The number is $i\033[0m" done
-
案例2,累加
#!/bin/bash #Use: for循环累加 #Auther: wl_it #Date: 2020.05.08 #定义一个变量 sum=0 for ((i=1; i<=100; i++)) do #注意“=”号两边不能有空格 #"+"号两边要添加空格 #expr 计算两个数相加 sum=`expr $i + $sum` done echo "sum is $sum"
sh -x for_sum.sh #查看脚本的执行变化
-
案例3,循环压缩文件
#!/bin/bash #Use: for循环压缩文件 #Author: wl_it #Date: 2020.05.08 #查找当前目录下的.sh文件 for i in `find . -name "*.sh"` do #创建一个存储目录 if [ ! -d test01 ]; then mkdir test01 fi tar -czvf test01/$i.zip $i done
-
案例4,循环解压缩文件
#!/bin/bash #Use: for循环 解压压缩文件 #Author: wl_it #Date: 2020.05.08 for i in `find test01 -name "*.zip"` do #创建一个存储目录 if [ ! -d test02 ];then mkdir test02 fi tar -xzvf $i -C test02 done
while循环
-
while循环累加
#!/bin/bash #Use: while循环测试1 #Author: wl_it #Date: 2020.05.12 i=1 while [[ $i -lt 10 ]] do echo "The num is $i" ((i++)) done
-
while循环读取
#!/bin/bash #Use: while循环测试2 #Author: wl_it #Date: 2020.05.12 while read line do echo $line done</etc/hosts
-
while循环输出
#!/bin/bash #Use: while循环测试3 #Author: wl_it #Date: 2020.05.12 while read line do ip=`echo $line|awk '{print $2}'` echo -e "\033[32mscp -r /tmp/test.txt root@$ip:/tmp\033[0m" done<list.txt
until循环
until循环和while的判断条件刚好相反,不满足条件就执行,满足条件就退出
#!/bin/bash
#Use: until语句测试
#Author: wl_it
#Date: 2020.05.13
a=10
#直到满足条件时 才退出 和while循环是相反的
until [[ $a -lt 0 ]]
do
echo $a
((a--))
done
case语句
#!/bin/bash
#Use: case语句测试
#Author: wl_it
#Date: 2020.05.13
case $1 in
Java )
echo "wait install Java"
;;
Nginx )
echo "wait install Nginx"
;;
Redis )
echo "wait install Redis"
;;
* )
echo -e "\033[32m Use $0 Java|Nginx|Redis|Help\033[0m"
esac
case+select语句
#!/bin/bash
#Use: case语句测试
#Author: wl_it
#Date: 2020.05.13
#PS3是一个固定的变量 专门用在select语句中输出信息
PS3="请选择您的操作:"
select i in "Java" "Nginx" "Redis"
do
case $i in
Java )
echo "wait install Java"
;;
Nginx )
echo "wait install Nginx"
;;
Redis )
echo "wait install Redis"
;;
* )
echo -e "\033[32m Use $0 Java|Nginx|Redis|Help\033[0m"
esac
done