shell指令碼 選擇 迴圈結構

2021-09-20 10:26:44 字數 1692 閱讀 7439

一、if語句

# 用法1

if confition; then

command...

fi# 用法2

if condition; then

command...

else

command...

fi# 用法3

if condition1; then

command...

elif condition2; then

command...

...else

command...

fi

二、case語句

case varname in

pattern1)

command...

;;pattern2)

command...

;;...

*) command...

esac

#注:pattern支援glob

三、while迴圈

# 用法1

while condition; do

commmand...

done

# 用法2,從指定檔案逐行讀取內容賦值給varline變數

while read varline; do

command...

done < /filepath

四、for迴圈

# 用法1,從變數列表逐個讀取資料

for varname in varlist; do

command...

done

# 用法2,類似c語言中的for用法

for ((初始條件;控制條件;變數修正)); do

command...

done

# 控制條件:支援類似 i<=10 這種格式

# 變數修正:支援 i++ 這種格式

五、until迴圈

#條件不滿足進入迴圈,條件滿足後跳出迴圈

until condition; do

command...

done

注:迴圈均支援continue與break,if,while,until條件中支援布林型值

指令碼例子:隨機生成10個隨機數,並排序

#!/bin/bash

#declare -a nums

# 生成隨機數並存入陣列

for i in ; do

nums[$i]=$random

done

echo "the 10 numbers are:$"

# 排序並輸出

for i in ; do

for((j=$[$i+1];j<=9;j++)); do

if [ $ -lt $ ]; then

temp=$

nums[$i]=$

nums[$j]=$temp

fidone

done

echo "after sorting:$"

shell指令碼 for迴圈

迴圈語句 while對於要求控制迴圈次數 操作物件按數字順序編號,按特定條件執行重複操作。重複測試某個條件時,只要條件成立就會反覆執行 無限 除非強制終止,或者exit語句退出指令碼 for迴圈語句 需要指定乙個變數以及可以取值的取值列表,針對每乙個不同的取值執行相同的命令序列,直到變數值用盡,退出...

shell指令碼 迴圈

迴圈有三種for,while,until,前兩種多種語言都有,大同小異,最後那種用的少,咱們就不說了 老規矩,上來先看 塊 root localhost scripts bash ceshi.sh 12 3456 78910 root localhost scripts cat ceshi.sh b...

shell 指令碼 迴圈

shell for 迴圈參考 linux下shell的for迴圈語句 shell逐行讀取檔案的3種方法 for迴圈語法 for var in item1 item2 itemn do command donefor迴圈 路徑查詢 在 mx資料夾有檔案 check list md5result tes...