四 Shell基礎知識 流程控制語句

2021-09-25 21:41:54 字數 2625 閱讀 6042

########if 語法

if condition

then

command1

fi#########if else 語法

if condition

then

command1

else

command

fi#####if else-if else 語法

if condition1

then

command1

elif condition2

then

command2

else

commandn

fi############例項,a 小於 b

a=10

b=20

if [ $a == $b ]

then

echo "a 等於 b"

elif [ $a -gt $b ]

then

echo "a 大於 b"

elif [ $a -lt $b ]

then

echo "a 小於 b"

else

echo "沒有符合的條件"

fi

#######for迴圈一般格式

for var in item1 item2 ... itemn

do command1

done

###########例項

for loop in 1 2 3 4 5

do echo "the value is: $loop"

done

#while迴圈可用於讀取鍵盤資訊。下面的例子中,輸入資訊被設定為變數film,按結束迴圈。 

echo '按下 退出'

echo -n '輸入你最喜歡的**名: '

while read film

do echo "是的!$film 是乙個好**"

done

#第一種

while :

do command

done

#第二種

while true

do command

done

#第三種

for (( ; ; ))

until 迴圈執行一系列命令直至條件為 true 時停止。until 迴圈與 while 迴圈在處理方式上剛好相反。

until condition

do command

done

condition 一般為條件表示式,如果返回值為 false,則繼續執行迴圈體內的語句,否則跳出迴圈。

a=0

until [ ! $a -lt 10 ]

do echo $a

a=`expr $a + 1`

done

shell case語句為多選擇語句。可以用case語句匹配乙個值與乙個模式,如果匹配成功,執行相匹配的命令。case語句格式如下:

case 值 in

模式1)

command1

;;模式2)

command1

;;esac

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

break命令允許跳出所有迴圈(終止執行後面的所有迴圈)。

下面的例子中,指令碼進入死迴圈直至使用者輸入數字大於5。要跳出這個迴圈,返回到shell提示符下,需要使用break命令。

while :

do echo -n "輸入 1 到 5 之間的數字:"

read anum

case $anum in

1|2|3|4|5) echo "你輸入的數字為 $anum!"

;;*) echo "你輸入的數字不是 1 到 5 之間的! 遊戲結束"

break

;;esac

done

continue命令與break命令類似,只有一點差別,它不會跳出所有迴圈,僅僅跳出當前迴圈。

while :

do echo -n "輸入 1 到 5 之間的數字: "

read anum

case $anum in

1|2|3|4|5) echo "你輸入的數字為 $anum!"

;;*) echo "你輸入的數字不是 1 到 5 之間的!"

continue

echo "遊戲結束"

;;esac

done

Python基礎知識 流程控制

語句的分類 a.單行 一行的python a1 print a1 b.塊 多行的語句組成的一組 def a1 print x print x print x print x class b2 var1 1 var2 2 if true print x print x print x 流程控制的分類 ...

python流程控制基礎知識總結

迴圈控制 迴圈巢狀 執行的流程 if語句在執行時,會先對條件表示式進行求值判斷,如果為true,則執行if後的語句 如果為false,則不執行 語法 if 條件表示式 塊 塊 塊中儲存著一組 同乙個 塊中的 要麼都執行要麼都不執行 塊以縮排開始,直到 恢復到之前的縮排級別時結束 塊就是一種為 分組的...

Ansible playbook 流程控制語句

1.when條件判斷 root test2 playbook cat test.yml hosts all remote user root tasks name shut down the db server service name mysqld state stopped when ansib...