简体   繁体   English

Unix bash shell脚本-在“ for”循环中迭代数组

[英]Unix bash shell script - Iterating an array in a 'for' loop

I have the following test script: 我有以下测试脚本:

#!/bin/sh

testArray=(A,B,C,D,E)
currentValue=''
tempValue=x

for i in "${testArray[@]}"
    do
        currentValue=$i

        echo "Processing " ${currentValue}

        if [ ${currentValue}==A ]
        then
            tempValue="$i 123"
        else
            tempValue=$i
        fi

        echo "Current loop " ${tempValue} 
        echo `date`

    done

When i test it, the output that i get is 当我测试它时,我得到的输出是

Processing  A,B,C,D,E
Current loop  A,B,C,D,E 123
Mon Dec 2 20:33:26 GMT 2013

It looks like the 'for' loop in Bash works somehow differently to what i am used to as i was expecting the following output (ie whatever is in the 'for' loop to be repeated for each of the array elements) 看来Bash中的“ for”循环的工作方式与我惯于期待以下输出的方式有所不同(即,对于每个数组元素重复“ for”循环中的内容)

Processing  A
Current loop  A 123
Mon Dec 2 20:29:44 GMT 2013

Processing  B
Current loop  B
Mon Dec 2 20:29:45 GMT 2013

Processing  C
Current loop  C
Mon Dec 2 20:29:46 GMT 2013

Processing  D
Current loop  D
Mon Dec 2 20:29:47 GMT 2013

Processing  E
Current loop  E
Mon Dec 2 20:29:48 GMT 2013
  • Why is the 123 at the end? 为什么最后是123?
  • Why is the date command executed only once and not for each iteration 为什么date命令只执行一次而不是每次迭代执行
  • What do i do to make each iteration work correctly. 我该怎么做才能使每个迭代正常工作。

Basically what i am trying to achieve is to write a script that iterates through an array list and execute the same command based on different parameters dependent on the value of the current item in the array. 基本上,我想实现的目标是编写一个遍历数组列表的脚本,并根据依赖于数组中当前项值的不同参数执行同一命令。 I wrote the above script to try and understand how the for loop works but i am not getting the output i was expecting. 我写了上面的脚本来尝试了解for循环的工作原理,但是我没有得到期望的输出。

This line 这条线

testArray=(A,B,C,D,E)

creates an array with a single element, namely the string 'A,B,C,D,E'. 创建一个具有单个元素的数组,即字符串'A,B,C,D,E'。 Array elements are separated by whitespace, not commas. 数组元素由空格而不是逗号分隔。 Use 采用

testArray=(A B C D E)

You'll also need to add whitespace to your if statement (and technically, you should use = inside [...] , not == , as well as quote the parameter expansion): 您还需要空格添加到您if语句(和技术,你应该使用=[...]而不是== ,以及报价参数扩展):

if [ "${currentValue}" = A ]

One more way 另一种方式

Change your loop to: 将循环更改为:

for i in `echo ${testArray} | tr "," " "`

As Suggested by chepner Change conditional statement to: 根据chepner的建议将条件语句更改为:

if [ "${currentValue}" = A ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM