1

I have the following code:

commit_hashes_raw=(`git cherry origin/Server_Dev`)
echo ${#commit_hashes_raw[@]}
echo ${commit_hashes_raw[@]}

that is producing the following output:

2
+ 6f0de9d07538db5d6428acd083c4a4527751596b

The first line is supposed to be the size of the array and the second is the contents. The obvious problem here is the discrepancy between the two values though. I've run this on another data set and a 50 element array was being reporting by the middle line as 100 elements long.

Am I using the wrong method for finding the size or is there something funky with my array?

4

2 回答 2

3

您的数组有两个元素 -+然后是哈希。从命令输出设置数组时,元素是空格分隔的,而不是换行分隔的。

你可以这样做:

commit_hashes_raw=($(git cherry origin/Server_Dev | awk '{print $NF}'))

或者,在不调用 shell 的情况下效率会降低:

commit_hashes_raw=()
while read plus hash; do 
  commit_hashes_raw+=("$hash")
done < <(git cherry origin/Server_Dev)
于 2012-11-19T14:09:17.560 回答
1

在我看来,这些+符号正在向您的数组添加额外的元素。您可以在创建数组时尝试将它们过滤掉。就像是:

commit_hashes_raw=(`git cherry origin/Server_Dev | cut -d' ' -f2`)
于 2012-11-19T14:10:54.373 回答