遍历关联数组并将值用于另一个操作?

Loop over an associative array and use the values for another action?

第一次写 bash 脚本。我只是从 Whosebug 问题中找到的零碎示例。

问题:如何将声明的关联数组imagetable与调整大小的脚本结合起来,以便它根据键值循环操作。

关联数组:

declare -A imagetable
imagetable=(
    ["custom-insights-laptop_1x.png"]   937x508
    ["custom-insights-laptop_2x.png"]   1874x1015
)

调整脚本大小

#!/bin/bash

#replace this -name value from imagetable
RETINA_IMAGES=`find . -name "custom-insights-laptop_1x.png"`

for retina_path in $RETINA_IMAGES
do
  target_path="${retina_path%.png}.png"

  #replace the -resize value from imagetable.
  convert -resize 937x508 $retina_path $target_path 

  echo "Converted ${retina_path} to ${target_path}"
done

我认为您只需要一些代码帮助,这似乎是最简单的,您不需要关联数组:

imgfile[0]="fileA.png"
imgfile[1]="fileB.png"
imgfile[2]="fileC.png"

for f in ${imgfile[@]}
do
    IMGSET=$(find . -name "$f")
    #other iterative code here
done

我想我理解你的需求,但我不清楚你的需求RETINA_IMAGES=$(find .. )

这一定能帮到你。

declare -A imagetable
imagetable=(
    [custom-insights-laptop_1x.png]=937x508
    [custom-insights-laptop_2x.png]=1874x1015
)

for i in ${!imagetable[*]} ; do
   echo "#dbg: i = $i and ${imagetable[$i]}=${imagetable[$i]}"

   sz=${imagetable[$i]}
   convert -resize "${sz}" "$retina_path" "$target_path"
done

像我在转换行上所做的那样,通过对变量的 dbl-quoting 使用避免整个 class 的 shell 脚本错误。

如果您需要进一步的帮助,请发表评论。

你可以通过做

学到很多关于关联数组的知识
echo ${!arr[*]} 
echo ${arr[*]}
echo ${#arr[*]}
echo ${arr[key]}

编辑

所以更进一步,不需要将文件名另存为 RETINA_IMAGES(感谢@MarkSetchell,我现在明白了;-)

试试

fileTarget="custom-insights-laptop_1x.png"
find . -name "$fileTarget" \
| while read retina_path ; do
  target_path="${retina_path%.png}.png"

  #replace the -resize value from imagetable.
  convert -resize ${imagetable[$fileTarget]} $retina_path $target_path 

  echo "Converted ${retina_path} to ${target_path}"
done 

然后您可以对所有 ${!imagetable[*]} 值进行 for 循环,设置 $fileTarget.

IHTH