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

 大眼-猫_945 发布于 2023-02-13 13:01

我有以下测试脚本:

#!/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

当我测试它时,我得到的输出是

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

看起来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

为什么123最后?

为什么date命令只执行一次而不是每次迭代

我该怎么做才能使每次迭代正常工作.

基本上我想要实现的是编写一个迭代数组列表的脚本,并根据不同的参数执行相同的命令,这些参数取决于数组中当前项的值.我写了上面的脚本试图理解for循环是如何工作的,但我没有得到我期待的输出.

1 个回答
  • 这条线

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

    创建一个包含单个元素的数组,即字符串'A,B,C,D,E'.数组元素由空格分隔,而不是逗号.使用

    testArray=(A B C D E)
    

    您还需要在if语句中添加空格(从技术上讲,您应该使用=内部[...],而不是==引用参数扩展):

    if [ "${currentValue}" = A ]
    

    2023-02-13 13:04 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有