• Shell for循环


    与其他编程语言类似,Shell支持for循环。

    for循环一般格式为:

    for 变量 in 列表
    do
        command1
        command2
        ...
        commandN
    done

    列表是一组值(数字、字符串等)组成的序列,每个值通过空格分隔。每循环一次,就将列表中的下一个值赋给变量。

    in 列表是可选的,如果不用它,for 循环使用命令行的位置参数。

    例如,顺序输出当前列表中的数字:

    #!/bin/bash
    
    
    for loop in 1 2 3 4 5
    do
        echo "The value is:$loop"
    done

    运行结果:

    The value is:1
    The value is:2
    The value is:3
    The value is:4
    The value is:5
    #!/bin/bash
    
    num=1
    for str in 'This is a string' 'test'
    do
      echo $num
       num=$[$num+1]
       echo $str
    done
    
    
    
    num=1
    for str in 'This is a string'
    do
      echo $num
       num=$[$num+1]
       echo $str
    done

    运行结果:

    1
    This is a string
    2
    test
    1
    This is a string

    显示主目录下以 .bash 开头的文件:

    #!/bin/bash
    
    
    for FILE in $HOME/.bash*
    do
      echo $FILE
    done
    
    
    
    for FILE in $HOME/.bash* ; do  echo $FILE
    done

    运行结果:

    /root/.bash_history
    /root/.bash_logout
    /root/.bash_profile
    /root/.bashrc

    普通的for循环

    #!/bin/bash
    echo `expr 4 * 4`
    
    for ((i=1; i <= 10; i++))
    do
       echo $(expr $i * 4)
    done
    ~       

    方法1:
        for 变量 in 常量列表; do 一些命令; done;

    for file in $(ls);do echo $file;done
    for i in 1 2 3 4 5;do echo $i; done;

    方法2:
        for (( 变量初始化; 条件判断; 变量自变 )); do 一些命令; done;
       

    for((i=0; i<10; i++)); do echo $i; done
    #!/bin/bash
    
    MAX=10
    
    for ((i=0; i < MAX; i++))
    do
        echo $i
    done
    
    
    
    
    for ((i=0; i < $MAX; i++))
    do
        echo $i
    done
    #/bin/bash
    
    
    MAX=10
    
    for ((i=0; i < MAX; i++))
    do
       echo $(expr $i * $i)
       echo $[$i * $i]
    done
  • 相关阅读:
    C#图形编程
    深入浅出话事件(上)
    .NET名称空间对应的类集
    Equals() 和运算符 == 的重写准则(C# 编程指南)
    Implement EventArgs
    CLS(公共语言规范)的CLSCompliant(跨语言调用)
    学习MSCOREE.dll是托管程序的入口点
    设计模式之原型模式代码示例
    The disk cannot be added to Cluster Shared Volumes because it does not have any suitable partitions
    RAID小结
  • 原文地址:https://www.cnblogs.com/ghgyj/p/4023488.html
Copyright © 2020-2023  润新知