Shell 流程控制案例

2021-09-24 05:45:31 字數 1199 閱讀 5733

複習shell流程控制語句!

迴圈遍歷檔案每一行:流程控制語句

定義檔案:

aaa 111

bbb 222

ccc 333

#!

/bin/bash

num=

0 #想列印行號,就必須先定義乙個行號變數

oldifs=$ifs

ifs=$'\n'

for i in `cat file.txt`;

do echo $i;

((num++))

done

echo "num:$num"

ifs=$oldifs

最後我們執行該檔案驗證:

[root@node1 shell]# ./readfile.sh

aaa 111

bbb 222

ccc 333

num:

3

#!

/bin/bash

num=

0lines=`cat file.txt | wc -l`

for(

(i=1

;i<=lines;i++))

;doline=`head -$i file.txt | tail -

1` echo $line

((num++))

done

echo "num:$num"

#!

/bin/bash

num=

0while read line;

do echo $line

((num++))

done echo "num:$num"

#!

/bin/bash

num=

0cat file.txt |

while read line;

do echo $line

((num++))

done

echo "num:$num"

這種實現方式,雖然file都讀出來了,但是num卻輸出了0;因為管道「|」,它會建立乙個bash位於子程序,不管在子bash中怎麼折騰,都不會影響父bash的值。

Shell流程控制

case迴圈 if condition condition then statements if true 1 elif condition condition then statements if true 2 else statements if all else fails fi注 方括號中的...

Shell 流程控制

shell的流程控制不可為空,如果else分支沒有語句執行,就不要寫這個else。if 語句語法格式 if condition then command1 command2 commandn fi寫成一行 適用於終端命令提示符 if ps ef grep c ssh gt 1 then echo t...

Shell流程控制

shell 流程控制 if else if語法格式 if condition then command1 command2 fi 末尾的fi就是if倒過來拼寫 if else語法 if condition then command1 command2 else command1 fi if else...