bash 有两种 for 语法,一种是类似于C语言的数值型语法,另一种是 for in 语法。

for in 的语法格式为:

  for <variable name> in <a list of items>;do <some command> $<variable name>;done;

示例:

  for name in joey suzy bobby;do echo $name;done
  for i in $(ls *.pdf); do
  mv $i $(basename $i .pdf)_$(date +%Y%m%d).pdf
  done
  for i in web{0..10} db{0..2} balance_{a..c};do echo $i;done

  web0
  web1
  web2
  web3
  web4
  web5
  web6
  web7
  web8
  web9
  web10
  db0
  db1
  db2
  balance_a
  balance_b
  balance_c
  for i in web-{us,ca}-{0..3};do echo $i;done
  web-us-0
  web-us-1
  web-us-2
  web-us-3
  web-ca-0
  web-ca-1
  web-ca-2
  web-ca-3
  $ cat somelist
  first_item
  middle_things
  foo
  bar
  baz
  last_item

  $ for i in `cat somelist`;do echo "ITEM: $i";done
  ITEM: first_item
  ITEM: middle_things
  ITEM: foo
  ITEM: bar
  ITEM: baz
  ITEM: last_item
  $ for i in file{1..3};do for x in web{0..3};do echo "Copying $i to server $x"; scp $i $x; done; done
  Copying file1 to server web0
  Copying file1 to server web1
  Copying file1 to server web2
  Copying file1 to server web3
  Copying file2 to server web0
  Copying file2 to server web1
  Copying file2 to server web2
  Copying file2 to server web3
  Copying file3 to server web0
  Copying file3 to server web1
  Copying file3 to server web2
  Copying file3 to server web3

https://www.redhat.com/sysadmin/bash-scripting-loops