shell 编程 (11)流程控制

本文深入探讨了Shell脚本中的流程控制结构,包括if-else条件判断、for循环、while循环、until循环、case选择结构及continue/break语句的使用方法与实例。适合于初学者和有经验的脚本开发者作为参考。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

sh脚本的流程控制不可为空,如else后如果没有需要执行的语句,则不要写else

1. if-else

# 适用于脚本形式
if condition
then
  command1
  command2
  ...
  commandn
fi

# ---------------------
if condition1
then
  command1
elif condition2
then
  command2
else
  commandn
fi

# 适用于命令行
if [ 数值计算 ]; then command; fi

注:

condition两边需用[]括起来

eg:

[root@k8s-master test6]# cat t0.sh 
#!/bin/bash

n1=$[2+3]
n2=$[2*3]

if test $[n1] -eq $[n2]
then
  echo "test $[n1] -eq $[n2]: true"
else
  echo "test $[n1] -eq $[n2]: false"
fi
[root@k8s-master test6]# sh t0.sh 
test 5 -eq 6: false
[root@k8s-master test6]# 

2. for

格式:

# 适用于脚本形式
for var in item1 time2 ... itemN
do
  command1
  command2
  ...
  commandN
done

# 适用于命令行形式
for var in item1 item2 ... itemN; do command1; command2... ; done

eg:

[root@k8s-master test6]# for var in 1 2 3 4 5; do echo "The value is: $var"; done
The value is: 1
The value is: 2
The value is: 3
The value is: 4
The value is: 5
[root@k8s-master test6]# 
[root@k8s-master test6]# for str in 'hello world'; do echo "$str\n"; done
hello world\n
[root@k8s-master test6]# 

3. while

格式:

while condition
do
  command
done

eg:

[root@k8s-master test6]# ./t1.sh 
1
2
3
4
5
[root@k8s-master test6]# cat t1.sh 
#!/bin/bash

i=1
while (( $i <= 5))
do
  echo $i
  let i++
done
[root@k8s-master test6]# 


[root@k8s-master test6]# ./t2.sh 
ctrl+d to exit
your like actor:tom
actor: tom
jack
actor: jack
[root@k8s-master test6]# cat t2.sh 
#!/bin/bash
echo 'ctrl+d to exit'
echo -n 'your like actor:'
while read actor
do
  echo "actor: $actor"
done
[root@k8s-master test6]# 

 

4. until

格式:

until condition
do
  command
done

eg:

[root@k8s-master test6]# ./t3.sh 
0
1
2
3
4
5
6
7
8
9
[root@k8s-master test6]# cat t3.sh 
#!/bin/bash

i=0

until [ ! $i -lt 10 ]
do
  echo $i
  i=$[i+1]
done
[root@k8s-master test6]# 

 

5. case

格式:

case val in
pattern1)
  command1
  command2
  ...
  commandN
  ;;
pattern2)
  command1
  command2
  ...
  commandN
  ;;
esac

eg:

[root@k8s-master test6]# ./t4.sh 
input a num between 1-2:
3
input not 1 or 2
[root@k8s-master test6]# cat ./t4.sh 
#!/bin/bash

echo 'input a num between 1-2:'

read n
case $n in
  1)  echo 'input 1'
  ;;
  2) echo 'input 2'
  ;;
  *)
    echo 'input not 1 or 2'
  ;;
esac
[root@k8s-master test6]# 



 

6. continue/break

[root@k8s-master test6]# ./t5.sh 
input 1 or 2
1
input: 1
2
input: 2
3
not 1 or 2 break
[root@k8s-master test6]# cat t5.sh 
#!/bin/bash

echo 'input 1 or 2'


while true
do
  read n
  if [ $n -ne 1 -a $n -ne 2 ]
  then
    echo 'not 1 or 2 break'
    break
  else
    echo "input: $n"
  fi

done 
[root@k8s-master test6]# 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值