gpt4 book ai didi

bash - 如何在bash脚本中创建for循环?

转载 作者:行者123 更新时间:2023-12-04 04:34:03 25 4
gpt4 key购买 nike

通常在 bash 脚本中编写 for 循环时,我会这样写:

FILE[1]=/tempA/aaa

FILE[2]=tempB/bbb

for FILES in `ls -1 ${FILE[@]}`
do
echo $FILES
done

这将根据我初始化 FILE 的数量显示 FILE,因为它在数组中。
我需要创建一个 bash 脚本来将文件从一个目录复制到另一个目录。

假设是这样的:
SOURCE[1]=/tempA/source/aaa

SOURCE[2]=/tempB/source/bbb


DEST[1]=/tempA/dest/

DEST[2]=/tempB/dest/

我需要从 source[1] 复制到 dest[1],也需要从 source[2] 复制到 dest[2]。所以我的问题是如何编写 FOR 循环?或者除了 for 循环之外还有另一种方法吗?

谢谢!

最佳答案

您可以使用 for循环遍历数组:

$ SOURCE=( /tempA/source/aaa /tempB/source/bbb )      # declare SOURCE array
$ DEST=( /tempA/dest /tempB/dest ) # declare DEST array
$ for i in ${!SOURCE[@]}; do echo "${SOURCE[$i]}" "${DEST[$i]}"; done
/tempA/source/aaa /tempA/dest
/tempB/source/bbb /tempB/dest

根据需要执行的操作,替换 echo使用适当的命令。 (您可以以上述形式声明数组,从而无需逐一声明数组元素。)

关于bash - 如何在bash脚本中创建for循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20063078/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com