shell 程式設計 for in 迴圈

2021-05-24 05:09:39 字數 2554 閱讀 1497

for in 格式

for 無$變數 in 字串

do$變數

done

一簡單的字串 列舉遍曆法,利用for in格式對字串按空格切份的功能

services="80   22   25   110   8000   23   20   21   3306   "

for   x   in   $services    

do     

iptables   -a   input   -p   tcp   --dport   $x   -m   state   --state   new   -j   accept     

done 

for variable in values   --------字串陣列依次賦值

#!/bin/sh

for i in a b c           字串列表a b c 

字串用空格分隔,沒有括號,沒有逗號, 然後迴圈將其依次賦給變數i

變數沒有$

doecho "i is $i"

done  

[macg@machome ~]$ sh test.sh

i is a

i is b

i is c

for in 裡,變數和*不等價

#!/bin/bash

for i in *.h ;

docat $.h

done  

[macg@vm test]$ ./tip.sh

cat: *.h.h: no such file or directory 

$i代表的是整個路徑,而不是*.h裡的.h前面的部分 改正

#!/bin/bash

for i in *.h

docat $i

done  

[macg@vm test]$ echo hahaha >>1.h

[macg@vm test]$ echo ha >>2.h

[macg@vm test]$ ./tip.sh

hahaha

ha    

例2:for i in /etc/profile.d/*.sh 

do$i

done  

$i代表的是/etc/profile.d/color.sh,

/etc/profile.d/alias.sh, /etc/profile.d/default.sh

for in 對(命令列,函式)引數遍歷

test()

$*是字串:以"引數1 引數2 ... " 形式儲存所有引數 

$i是變數i的應用表示

[macg@machome ~]$ sh test.sh p1 p2 p3 p4

i is p1

i is p2

i is p3

i is p4 

for in語句與萬用字元*合用,批量處理檔案

批量改檔名

[root@vm testtip]# ls

aaa.txt  ccc.txt  eee.txt  ggg.txt  hhh.txt  jjj.txt  lll.txt  nnn.txt

bbb.txt  ddd.txt  fff.txt  go.sh    iii.txt  kkk.txt  mmm.txt  ooo.txt

[root@vm testtip]# cat go.sh

for i in *.txt                 *.txt相當於乙個字串陣列,依次迴圈賦值給i

domv "$i" "$i.bak"       

done

[root@vm testtip]# sh go.sh

[root@vm testtip]# ls

aaa.txt.bak  ccc.txt.bak  eee.txt.bak  ggg.txt.bak  hhh.txt.bak  jjj.txt.bak  lll.txt.bak  nnn.txt.bak bbb.txt.bak  ddd.txt.bak  fff.txt.bak  go.sh        iii.txt.bak  kkk.txt.bak  mmm.txt.bak  ooo.txt.bak

for in語句與` `和$( )合用,利用` `或$( )的將多行合為一行的缺陷,實際是合為乙個字串陣列

for i in $(ls *.txt)

doecho $i

done

[macg@machome ~]$ sh test

111-tmp.txt

111.txt

22.txt

33.txt

或者說,利用for in克服` `和$( ) 的多行合為一行的缺陷

利用for in 自動對字串按空格遍歷的特性,對多個目錄遍歷

list="rootfs usr data data2"

for d in $list; do         

mount /backup/$d

rsync -ax --exclude fstab --delete /$d/ /backup/$d/

umount /backup/$d

done    

shell程式設計 for in 迴圈

for in 格式 for 無 變數 in 字串 do 變數 done 一簡單的字串 列舉遍曆法,利用for in格式對字串按空格切份的功能 services 80 22 25 110 8000 23 20 21 3306 for xin services do iptables a input p...

shell程式設計 for in 迴圈

for in 格式 for無 變數 in字串 do 變數 done 一簡單的字串 列舉遍曆法,利用for in格式對字串按空格切份的功能 services 80 22 25 110 8000 23 20 21 3306 for x in services do iptables a input p ...

指令碼樂園 shell程式設計for in 迴圈

for in 格式 for 無 變數 in 字串 do 變數 done 一簡單的字串 列舉遍曆法,利用for in格式對字串按空格切份的功能 services 80 22 25 110 8000 23 20 21 3306 for x in services do iptables a input ...