查看: 2061|回复: 0
打印 上一主题 下一主题

Shell for循环

[复制链接]
跳转到指定楼层
沙发
发表于 2014-8-16 09:17:12 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
与其他编程语言类似,Shell支持for循环。
for循环一般格式为:
  1. for 变量 in 列表
  2. do
  3.     command1
  4.     command2
  5.     ...
  6.     commandN
  7. done
复制代码

列表是一组值(数字、字符串等)组成的序列,每个值通过空格分隔。每循环一次,就将列表中的下一个值赋给变量。
in 列表是可选的,如果不用它,for 循环使用命令行的位置参数。
例如,顺序输出当前列表中的数字:
  1. for loop in 1 2 3 4 5
  2. do
  3.     echo "The value is: $loop"
  4. done
复制代码
运行结果:
  1. The value is: 1
  2. The value is: 2
  3. The value is: 3
  4. The value is: 4
  5. The value is: 5
复制代码
顺序输出字符串中的字符:
  1. for str in 'This is a string'
  2. do
  3.     echo $str
  4. done
复制代码
运行结果:
  1. This is a string
复制代码
显示主目录下以 .bash 开头的文件:
  1. #!/bin/bash
  2. for FILE in $HOME/.bash*
  3. do
  4.    echo $FILE
  5. done
复制代码
运行结果:
  1. /root/.bash_history
  2. /root/.bash_logout
  3. /root/.bash_profile
  4. /root/.bashrc
复制代码


回复

使用道具 举报

您需要登录后才可以回帖 登录 | 加入因仑

本版积分规则

快速回复 返回顶部 返回列表