bash:associative array - 一个键的多个值

时间:2016-03-09 12:08:44

标签: arrays linux bash

我有GIT存储库,我有提交和标记。某些提交有2个或更多标记。我想创建关联数组,其中:

  • key = commit hash
  • value = tag(s)

我在GIT目录中运行的脚本:

#!/bin/sh
declare -A cc

echo "Fill 'cc' array:"
git for-each-ref --format='%(objectname) %(refname:short)' refs/tags | while read key value; do
  cc[$key]="${cc[$key]}${cc[$key]:+ }$value";
  echo "$key -> ${cc[$key]}"
done

echo "Print 'cc' array:"    
for ii in "${!cc[@]}"; do 
  echo "$ii -> ${cc[$ii]}"; 
done

输出:

$ ./cleaning.sh
Fill 'cc' array:
b41d8a63cb6434e76849a528604bd736458af839 -> 2014-07-30.v1
7b6b1523ff0bab428cb0fc65dc9249ae11a0dc52 -> 2014-08-13.v1
~
~
28dcd96836ce20773d046d49fa2e096245e6f6fa -> PRO SSPBE-9.6
e4b31b5fb541dd409d08e0a0b961f56e9e70821e -> SSPBE-9.7
Print 'cc' array:
$

while循环中的第一个'echo'正常工作并打印键和值。但是然后运行'for'循环,它应该将列表'cc'打印到stdout但是什么都不打印。它看起来像关联数组'cc'是空的。

修改

我看到子shell的问题在哪里。但是如果我使用这种语法:

echo "Fill 'cc' array:"
while read k v; do
  cc[$k]="${cc[$k]}${cc[$k]:+ }$v";
done < <(git for-each-ref --format='%(objectname) %(refname:short)' refs/tags)

echo "Print 'cc' array:"
for ii in "${!cc[@]}"; do echo "$ii -> ${cc[$ii]}"; done

所以我得到了:

$ ./cleaning.sh
Fill 'cc' array:
./cleaning.sh: line 39: syntax error near unexpected token `<'
./cleaning.sh: line 39: `done < <(git for-each-ref --format='%(objectname) %(refname:short)' refs/tags)'

有趣的是,当我从命令行运行它,所以它成功完成。

$ while read k v; do cc[$k]="${cc[$k]}${cc[$k]:+ }$v"; done < <(git for-each-ref --format='%(objectname) %(refname:short)' refs/tags)
$ for ii in "${!cc[@]}"; do echo "$ii -> ${cc[$ii]}"; done
164b1d93ee2f728e92be8d39aace814799c10a00 -> SSPBE-7.17 SSPBE-7.17
303c0deb4f32d224b28a305d54125b788f5ac75a -> SSPBE-7.21 SSPBE-7.21
~

编辑2 - 固定

解决了 - 我必须修复重定向:

 while read k v; do
  cc[$k]="${cc[$k]}${cc[$k]:+ }$v";
done <<< "$(git for-each-ref --format='%(objectname) %(refname:short)' refs/tags)"

0 个答案:

没有答案