展开
拓展 关闭
订阅号推广码
GitHub
视频
公告栏 关闭

shell流程控制

判断

  • fi
[root@VM-12-15-centos home]# vi test.sh
# 编写如下
a=100
b=100
if test $[a] -eq $[b] ; then echo "true"; fi

# 执行
[root@VM-12-15-centos home]# sh test.sh
true
  • if else
[root@VM-12-15-centos home]# vi test.sh
# 编写如下
a=100
b=101
if test $[a] -eq $[b] ;
then echo "true";                                                                                                       else echo "false";                                                                                                      fi       

# 执行
[root@VM-12-15-centos home]# sh test.sh
false
  • if else-if else
[root@VM-12-15-centos home]# vi test.sh
# 编写如下
a=10
b=20
if (( $a == $b ))
then
   echo "a 等于 b"
elif (( $a > $b ))
then
   echo "a 大于 b"
elif (( $a < $b ))
then
   echo "a 小于 b"
else
   echo "没有符合的条件"
fi  

# 执行
[root@VM-12-15-centos home]# sh test.sh
a 小于 b

循环

for循环
  • 顺序输出列表中的数字
[root@VM-12-15-centos home]# vi test.sh
# 编写如下
for loop in 1 2 3 4 5
do
    echo "The value is: $loop"
done

# 执行
[root@VM-12-15-centos home]# sh test.sh
The value is: 1
The value is: 2
The value is: 3
The value is: 4
The value is: 5
  • 顺序输出字符串中的字符
[root@VM-12-15-centos home]# vi test.sh
# 编写如下
for str in This is a string
do
    echo $str
done

# 执行
[root@VM-12-15-centos home]# sh test.sh
This
is
a
string
while循环
  • 案例
[root@VM-12-15-centos home]# vi test.sh
# 编写如下
int=1
while(( $int<=5 ))
do
    echo $int
    let "int++"
done

# 执行
[root@VM-12-15-centos home]# sh test.sh
1
2
3
4
5
无限循环
# 写法1
while :
do
    echo "test1"
    sleep 1  # 暂停一秒
done

# 写法2
while true
do
    echo "test2"
    sleep 1  # 暂停一秒
done

# 写法3
for (( ; ; ))  
do  
    echo "test3"  
    sleep 1  # 暂停一秒
done
until循环
[root@VM-12-15-centos home]# vi test.sh
# 编写如下
counter=0  
until [ $counter -ge 10 ]  
do  
    echo "计数器: $counter"  
    counter=$((counter+1))  
done

# 执行
[root@VM-12-15-centos home]# sh test.sh
计数器: 0
计数器: 1
计数器: 2
计数器: 3
计数器: 4
计数器: 5
计数器: 6
计数器: 7
计数器: 8
计数器: 9

# 脚本说明
# 计数器是否大于或等于10,初始条件为假,条件变为真,循环就会停止
case esac
  • 案例
[root@VM-12-15-centos home]# vi test.sh
# 编写如下
echo '输入 1 到 4 之间的数字:'
echo '你输入的数字为:'
read aNum
case $aNum in
    1)  echo '你选择了 1'
    ;;
    2)  echo '你选择了 2'
    ;;
    3)  echo '你选择了 3'
    ;;
    4)  echo '你选择了 4'
    ;;
    *)  echo '你没有输入 1 到 4 之间的数字'
    ;;
esac

# 执行
[root@VM-12-15-centos home]# sh test.sh
输入 1 到 4 之间的数字:
你输入的数字为:
2
你选择了 2
跳出循环
  • break
for i in {1..5}  
do  
    if [ $i -eq 3 ]; then  
        break  
    fi  
    echo $i  
done  
# 这将只打印1和2,因为当i等于3时,循环被break语句终止。
  • continue
for i in {1..5}  
do  
    if [ $i -eq 3 ]; then  
        continue  
    fi  
    echo $i  
done  
# 这将打印1、2、4和5,因为当i等于3时,当前迭代被continue语句跳过。
posted @ 2024-05-14 11:36  DogLeftover  阅读(1)  评论(0编辑  收藏  举报