Results 1 to 4 of 4
  1. #1
    Join Date
    May 2003
    Posts
    58

    Unanswered: script help needed

    I want to initialize variables in a loop as shown below (commented). It gives errors Ex: COUNT1=1: not found. Similarily the statement below it gives errors: 1=COUNT1: not found. etc...

    If I say for example,

    COUNT1=`echo "$ALLCOUNTS" | cut -d" " -f1`
    COUNT2=`echo "$ALLCOUNTS" | cut -d" " -f2` the variables initialize well.

    Can somebody please tell why?

    Code:
    #
    i=1 
    while [ $i -lt $COUNT_DESIRED ]
    do
        #COUNT$i=`echo "$ALLCOUNTS" | cut -d" " -f$i`
        [ -z $COUNT$i ] && COUNT$i=11
        ${allcounts[$i-1]}=COUNT$i
        i=`expr $i + 1`
    done

  2. #2
    Join Date
    Jan 2004
    Location
    Bordeaux, France
    Posts
    320
    You can do something like this :
    Code:
    i=1 
    while [ $i -le $COUNT_DESIRED ]
    do
        #COUNT$i=`echo "$ALLCOUNTS" | cut -d" " -f$i`
        eval Count=\$COUNT$i
        allcounts[$((i-1))]=${Count:-11}
        (( i += 1 ))
    done
    Jean-Pierre.

  3. #3
    Join Date
    May 2003
    Posts
    58
    Aigles, Thanks for the reply.

    i=1
    while [ $i -le 5 ]
    do
    COUNT$i=$i
    (( i+= 1 ))
    done

    Here my idea is just to initialize 5 variables dynamically. The above approach won't work. I tried using

    i=1
    while [ $i -le 5 ]
    do
    ((COUNT$i=$i))
    (( i+= 1 ))
    done

    it won't work either. Any ideas? Thanks.

  4. #4
    Join Date
    Jan 2004
    Location
    Bordeaux, France
    Posts
    320
    First approach
    Code:
    i=1
    while [ $i -le 5 ]
    do
       eval COUNT$i=$i
       (( i+= 1 ))
    done
    The second approach works fine for me, what is your problem ?
    execute with -x option to verify variable creation.

    Note: The two solutions works only with bash and ksh due to '(( ))' syntax usage.
    (( i+= 1)) can be replaced by i=`expr $i + 1`
    Jean-Pierre.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •