Shell执行流控制for、while、until、if、case语句5

Shell学习

学习shll脚本


一、for语句

for格式:

for
do
done

形势1

[root@trade sh]# cat 1.sh 
for i in {1..10}
do
echo $i
done
[root@trade sh]# sh 1.sh 
1
2
3
4
5
6
7
8
9
10

形势2

[root@trade sh]# cat 2.sh 
for i in $(seq 1 2 10)		#n从1到10 步长为2
do
echo $i
done
[root@trade sh]# sh 2.sh 
1
3
5
7
9

形势3

for ((i=0;i<10;i++))
do
echo $i
done
[root@trade sh]# cat 3.sh 
for ((i=0;i<10;i++))
do
echo $i
done
[root@trade sh]# sh 3.sh 
0
1
2
3
4
5
6
7
8
9

for语句脚本练习

check_host.sh
用此脚本检测 10 台与您当前主机直连主机是否网络通常
如果网络通常请显示主机的 ip 列表

for IP in 192.168.100.{10..20}
do
  ping -c1 -w1 $IP &>/dev/null && {
     echo 网络通畅的主机ip:$IP
     }
done
[root@trade sh]# sh check_host.sh 
网络通畅的主机ip:192.168.100.10

二、While语句

格式:
条件为真执行动作

while
do
done
[root@trade sh]# cat 4.sh 
while true
do
echo hello
exit
done
[root@trade sh]# sh 4.sh 
hello

三、until语句

格式:
条件为假执行动作

until
do
done
[root@trade sh]# cat 5.sh 
until false
do
echo hello
exit
done
[root@trade sh]# sh 5.sh 
hello

四、if语句

多次判定条件执行动作
格式:

if
then
else
fi
[root@trade sh]# cat 6.sh 
if [ $1 -lt 10 -a $1 -gt 0 ]
then 
     echo $1 is between 1-10
else
   echo error
fi
[root@trade sh]# sh 6.sh 9
9 is between 1-10

五、case

使用 case 语句改写 if 多分支可以使脚本结构更加清晰、层次分明。针对变量的不同取 值,执行不同的命令序列。

格式:

case 变量值 in
模式 1)
命令序列 1
;;
模式 2)
命令序列 2
;;
*)
默认命令序列
esac
[root@trade sh]# cat 7.sh   
case $1 in
   yan)
   echo yan
   ;;
   hhh)
   echo hhh
   ;;
   *)
   echo error
esac
[root@trade sh]# sh 7.sh hhh
hhh
[root@trade sh]# sh 7.sh yan
yan
[root@trade sh]# sh 7.sh 1  
error
[root@trade sh]# sh 7.sh 12
error

六、循环退出

continue	终止当前循环进入下一个循环
break		退出当前循环
exit		退出程序

七、脚本练习

check_file.sh
please input filename: file
file is not exist
file is file
file is direcory
此脚本会一直询问直到用戶输入 exit 为止

[root@trade sh]# cat check_file.sh 
while true
do
read -p "please input filename: " FILE
if [ $FILE = "exit" ]
then
    exit
elif [ ! -e $FILE ]
then
    echo $FILE is not exist!!
elif [ -f $FILE ]
then 
    echo $FILE is file
elif [ -d $FILE ]
then
    echo $FILE is directory
fi
done	
[root@trade sh]# sh check_file.sh 
please input filename: 1
1 is not exist!!
please input filename: 1.sh
1.sh is file
please input filename: test
test is directory
please input filename: exit
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值