shell脚本编程-结构化命令2-for命令

1、for命令

(1)语法
    for val in list; do
        commands
    done

  list参数提供了一些列用于迭代的值,val值依次赋值为list中的值,知道list轮询结束。

    commands可以是一条或多条shell命令,echo $val可以查看当前循环的值
(2)读取列表中的值
    $cat test
    #!/bin/bash
    # basic for command
    for test in A B C; do
        echo the next val is $test
    done
    $./test
    the next val is A
    the next val is B
    the next val is C
    每次for命令便利提供的值列表时, 会将列表中的下个值赋给$test变量。
    在最后一次迭代中,$test的值会在shell脚本中的剩余部分一直有效。
    当所要迭代的值中含有空格、单引号、双引号时,for命令不能识别其为值得一部分,可以采用两种方式处理:
        当遍历的值中出现空格、单引号时,可以通过在值两侧添加双引号以示区别;
        当遍历的值中出现单引号、双引号时,可以通过转义字符来讲其转义;
(3)从变量或命令读取值
    通常shell脚本遇到的情况是,将一系列的值存储在变量中,然后遍历整个变量列表
    
   $cat test
    #!/bin/bash
    # using a variable to hold the list
    list="A B C"
    list=$list" D"
    for test in $list; do
        echo the next val is $test
    done
    $./test
    the next val is A
    the next val is B
    the next val is C
    the next val is D
    向已知变量中增加值通过list=$list" D"实现,这个尾部添加文本的一个常用方法
    生成遍历列表的另一个方法是使用命令的输出,可以通过反引号来执行任何能产生输出的命令
    $cat test
    #!/bin/bash
    # reading value from a file
    file="alphabet"
    for test in `cat $file`; do
        echo the next val is $test
    done
    $./test
    the next val is A
    the next val is B
    the next val is C
(4)更改字段分隔符
    bash中定义了特殊的环境变量IFS,称为内部字段分隔符。默认情况下,bash会将空格、制表符、换行符作为字段分隔符。
    当我们在使用时,可以修改IFS的值已满足不同的情况。
    修改IFS值格式,如:IFS=$' ', IFS=:
    一般情况下载处理长脚本时,需要先将IFS的值保存在临时变量中,在使用完后再恢复它:
    IFS.OLD=$IFS
    IFS=$'
'
    <use the new IFS value in code>
    IFS=$IFS.OLD
    如果需要多个IFS字符,只需将它们在赋值时串起来即可:IFS=$' :;"',这样就可以把换行、冒号、分好、双引号都作为字符按分隔符处理。
(5)使用通配符遍历目录
    $cat test
    #!/bin/bash
    #iterate through all the files in a directory
    for file in /home/test/* ; do
        if [ -d "$file" ]; then
            echo "$file is a directory"
        elif [ -f "$file" ]; then
            echo "$file is a file"
        fi
    done
    linux中文件或目录中可以包含空格,所以file需要使用双引号"$file"。

2、循环处理文件数据

    遍历存数在文件中数据:使用循环语句和IFS变量。
    经典案例,处理/etc/passwd文件中的数据:
    #!/bin/bash
    #changing the IFS value
    IFS.OLD=$IFS
    IFS=$'
'
    for entry int `cat /etc/passwd`; do
        echo "val in $entry"
        IFS=:
        for value in $entry; do
            echo " $value"
        done
    done
    IFS=$IFS.OLD
    这个脚本使用两个不同的IFS值来解析数据,第一个IFS解析出文件中单独的行,内部for循环将IFS的值修改为冒号,解析出每行中的数据。
原文地址:https://www.cnblogs.com/hancq/p/5024561.html