LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Incrementing an array element in Shell scripting (https://www.linuxquestions.org/questions/linux-newbie-8/incrementing-an-array-element-in-shell-scripting-815992/)

ohijames 06-23-2010 04:06 PM

Incrementing an array element in Shell scripting
 
ch[1]=0; ch[2]=0; ch[3]=0; ch[4]=0; ch[5]=0; ch[6]=0; ch[7]=0; ch[8]=0; ch[9]=0; ch[10]=0;ch[11]=0; ch[12]=0; ch[13]=0; ch[14]=0; ch[15]=0 ch[16]=0; ch[17]=0; ch[18]=0; ch[19]=10; ch[20]=0;

I have an array ch and I want to increment each element in my array for the following if statement. I'm not sure I have the right array increment syntax but I have tried it in different ways ant it doesn't seem to work.
I tried ch[$1]++, ch[$1]+1, ch[$1++], ch[$1]+=1, ch[$1]=ch[$1]+1 none of these seem to work.


# while loop reading from read.txt for check list 1 - 15
for i in `seq 15`
do
a=`grep "${cl[$i]}" $file`
status=$?
if [[ $status = 0 ]];
then
echo -n -e "1 "
let ch[$i+1]
let k++
else
echo -n -e "0 "
fi
done

for l in `seq 20`
do
echo -n -e "${ch[$l]} "

done

Andrew Benton 06-23-2010 05:06 PM

Code:

((ch[$i]++))

rweaver 06-23-2010 05:06 PM

Enclose your code in [ code] [/ code] tags makes it a lot more readable (not so bad in this case, but helps if you have a lot of important indenting.)

Code:

#!/bin/bash
ch[1]=0
ch[2]=0
ch[3]=0
ch[4]=0
ch[5]=0
for i in $(seq 5); do
  for j in $(seq 5); do
    ch[$i]=$((${ch[$i]} + $j))
    echo "i: $i, j: $j, ch[\$i]: ${ch[$i]}"
  done
done

This code should explain it fairly well.

edit: The ABS has a lot of good information on using arrays in bash and the specifics of how to reference them: http://tldp.org/LDP/abs/html/arrays.html


All times are GMT -5. The time now is 07:38 PM.