gaofeng0210 发表于 2018-8-23 09:38:08

shell之for、while循环

  一、for循环
  # cat for.sh
  #!/bin/bash
  for i in `seq 1 10`; do
  echo "$i"
  done
  通过这个脚本就可以看到for循环的基本结构:
for 变量名 in 循环的条件; do  
   command
  
done
  # sh for.sh
  1
  2
  3
  4
  5
  6
  7
  8
  9
  10
  例2:
  # cat for2.sh
  #!/bin/bash
  for a in `ls`; do
  echo "$a"
  done
  # sh for2.sh
  case1.sh
  case.sh
  for2.sh
  for3.sh
  for.sh
  if1.sh
  if.sh
  例3
  # cat for3.sh
  #!/bin/bash
  for file in `vmstat`; do
  echo "$file"
  done
  for i in `cd /shell && ls`; do
  echo "$i"
  done
  引用系统命令需要加反引号,其他不用
  # for i in 1 4 5 3 a a; do echo "$i"; done
  1
  4
  5
  3
  a
  a
  二、while循环
  # cat while.sh
  #!/bin/bash
  a=6
  while [ $a -ge 1 ]; do
  echo $a
  a=$[$a-1]
  done
  while 循环格式也很简单:
while条件; do  

  
          command
  
done
  # sh while.sh
  6
  5
  4
  3
  2
  1
  例2
  # cat while2.sh
  #!/bin/bash
  while :; do
  seq 1 3
  done
  把循环条件拿一个冒号替代,这样可以做到死循环
  # sh while2.sh
  1
  2
  3
  1
  2
  3
  1
  2


页: [1]
查看完整版本: shell之for、while循环