共計 1984 個字符,預計需要花費 5 分鐘才能閱讀完成。
丸趣 TV 小編給大家分享一下 Shell 中如何實現流程控制,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!
Shell 流程控制
在 Linux 編程中,流程控制語句基本為 if、for、while、until、case 等條件的控制語句
if 控制
if 常用語法結構
If (表達式); then
echo ..........
else
echo ..........
fi
演示:
#!/bin/bash
num=10
if ((${num} 4));then
echo ${num} 大于 3
if test [${num} 4];then
echo ${num} 大于 4
fi
if 多重判斷
#!/bin/bash
num=10;
if [ $num -lt 8 ];then
echo ${num} 小于 8
elif [ ${num} -eq 10 ];then
echo ${num} 等于 10
elif [ ${num} -gt 11 ];then
echo ${num} 大于 10
echo 沒有符合的條件
fi;
for 循環
for 循環語法結構
For 變量 in 字符串
do
echo
done
演示:
#!/bin/bash
#定義一個數組
val=(1 2 3 4 5 6)
for i in ${val[*]} # 也可以直接 in `seq 6`
echo this is num: $i
done
輸出結果:
# 打印結果:this is num: 1
this is num: 2
this is num: 3
this is num: 4
this is num: 5
this is num: 6
演示 2:
#!/bin/bash
# 對查找文件批量打包
for i in `find /var/log -name “*.log”`
do
tar –czf 2019log.tgz $i
done
while 循環
while 語法結構
while (條件判斷)
do
echo
done
演示:
#!/bin/sh
i=1;
while(( $i = 10 ));do # 或者 while [ $i -le 10 ];do
echo $i;
let i++ # 或者 ((i++));
done;
輸出結果:
1
10
演示:
[root@localhost opt]# cat test.sh
#!/bin/sh
#打印文件內容
while read line
echo $line;
done /etc/hosts
until 循環
until 循環執行命令是需要條件為 true 時才退出,否知一直循環,[] 主要判斷 true 和 false
until 循環與 while 循環在處理方式相反,且 while 循環優于 until 循環
演示:
#!/bin/bash
i=1;
until [ ! $i -le 10 ];do
echo $i;
let i++ #((i++)) or (i=`expr $i + 1`)
done;
case 選擇語句
簡單演示:
#!/bin/sh
#author:
case $1 in
1|2|3|4) echo 你輸入數字為 $1
;;
*)
echo Usage:{$0 1 | 2 | 3 | 4 | help}
echo 你輸入數字不在服務區
;;
esac
簡單演示
注意:
break 直接跳出 while 循環體
continue 只會跳出當前循環, 不會跳出 while 循環
#!/bin/sh
#author:
while :
echo ------------------------
echo 輸入 1- 4 之間的數字:
echo 你輸入的數字為:
read num
case $num in
1|2|3|4) echo 你輸入數字為:${num} !!
;;
*)
#echo Usage:{$0 1 | 2 | 3 | 4 | help}
echo ------------------------
echo 你輸入數字不在服務區
break # continue
;;
done
select 選擇語句
#!/bin/sh
#author:
PS3= What you like most of the open source system?
select i in windows Linux Max
do
echo Your Select System: $i
done
# 目錄是否存在
if [ ! -d $BAK_DIR ];then
mkdir -p $BAK_DIR
#test 判斷文件
if test -e ${BAK_DIR}
echo 文件存在! echo 文件不存在!fi
看完了這篇文章,相信你對“Shell 中如何實現流程控制”有了一定的了解,如果想了解更多相關知識,歡迎關注丸趣 TV 行業資訊頻道,感謝各位的閱讀!
正文完