Bash:遍历数组以获取每个索引的值

时间:2016-12-01 20:14:07

标签: arrays bash shell loops iteration

该程序的主要目标是在用户选择的情况下模拟卡片的绘制次数,然后使用' *'打印出直方图。表示每张卡上的点击次数。但是,我遇到的问题是检索每个数组中的元素并打印与它们相关的星星。这就是我到目前为止所做的:

timelimit=5
echo -e "How many trials would you like to run? \c"
read -t $timelimit trials

if [ ! -z "$trials" ]
then
    echo -e "\nWe will now run $trials trials"
else
    trials=10
    echo -e "\nWe will now run the default amount of trials: $trials"
fi

count=1
MAXCARD=53
declare -a CARDARRAY

while [ "$count" -le $trials ]
do
    card=$RANDOM
    let "card %= MAXCARD"
    let "CARDARRAY[$card] += 1"
    let "count += 1"
done  
echo ${CARDARRAY[@]}

for (( i=0; i<${#CARDARRAY[@]}; i++));
do
    #declare "temp"="${CARDARRAY[$i]}"
    #echo "$temp"
    #for (( j=0; j<temp; j++));
    #do
    #echo "*"
    #done
    echo "$i"
done

显然,最后一个循环是我遇到麻烦的地方,目前是根据每张卡有多少次点击打印星星的最新尝试。

1 个答案:

答案 0 :(得分:2)

你非常接近。以下是我对你的剧本的解释:

#!/bin/bash
timelimit=5
printf %s 'How many trials would you like to run? '
read -t $timelimit trials

if [[ ! -z $trials ]] ; then
    printf '\nWe will now run %d trials\n' $trials
else
    trials=10
    printf '\nWe will now run the default amount of trials: %d\n' $trials
fi

count=1
MAXCARD=53
declare -a CARDARRAY

while (( trials-- )) ; do
    (( CARDARRAY[RANDOM % MAXCARD] += 1 ))
done  

printf '%s\n' "${CARDARRAY[*]}"

for (( i=0 ; i<MAXCARD ; i++ )) ; do
    printf %02d: $i

    for (( j=0 ; j<${CARDARRAY[i]:-0} ; j++ )) ; do
        printf %s '*'
    done
    printf '\n' ''
done

您可以使用set -xv查看每个步骤中正在运行的bash。