如何在 Ksh 中遍历多个字符串

How to iterate through multiple strings in Ksh

我希望使用一个 for 循环遍历多个字符串,以在 Unix 脚本中执行一系列文件复制操作。

所以给定一些表示目录的字符串:

file1="${HOME_PATH}/data1.dat"
file2="${HOME_PATH}/one/model1/data2.dat"
file3="${HOME_PATH}/two/model2/data3.dat"
file4="${HOME_PATH}/three/model3/data4.dat"
file5="${HOME_PATH}/three/model4/data5.dat"
file6="${HOME_PATH}/three/model5/data5.dat" 

我想将其中的每一个复制到特定目录:

dest1="${DEST_PATH}/data1.dat"
dest2="${DEST_PATH}/one/model1/data2.dat"
dest3="${DEST_PATH}/two/model2/data3.dat"
dest4="${DEST_PATH}/three/model3/data4.dat"
dest5="${DEST_PATH}/three/model4/data5.dat"
dest6="${DEST_PATH}/three/model5/data5.dat"

有没有办法像我在上面所做的那样列出每个文件位置,然后简单地按照...

行进行 for 循环
for each i in {1..6}
do
   cp file[i] dest[i]
done

您可以为此使用间接寻址:

for i in {1..6}
do
  file="file$i"
  dest="dest$i"
  echo "${!file} ${!dest}" #or whatever you want to do with each file
done

来自How can I use variable variables (indirect variables, pointers, references) or associative arrays?

BASH allows you to expand a parameter indirectly -- that is, one variable may contain the name of another variable:

 # Bash
 realvariable=contents
 ref=realvariable
 echo "${!ref}"   # prints the contents of the real variable
file[1]="${HOME_PATH}/data1.dat"
file[2]="${HOME_PATH}/one/model1/data2.dat"
file[3]="${HOME_PATH}/two/model2/data3.dat"
file[4]="${HOME_PATH}/three/model3/data4.dat"
file[5]="${HOME_PATH}/three/model4/data5.dat"
file[6]="${HOME_PATH}/three/model5/data5.dat" 

dest[1]="${DEST_PATH}/data1.dat"
dest[2]="${DEST_PATH}/one/model1/data2.dat"
dest[3]="${DEST_PATH}/two/model2/data3.dat"
dest[4]="${DEST_PATH}/three/model3/data4.dat"
dest[5]="${DEST_PATH}/three/model4/data5.dat"
dest[6]="${DEST_PATH}/three/model5/data5.dat"

for i in "${file[@]}"
do
    cp ${file[i]} ${dest[i]}
done