user553947
user553947

Reputation:

Problem with bash code

function dec_to_bin {   

if [ $# != 2 ]  
then
    return -1
else
    declare -a ARRAY[30]
    declare -i INDEX=0
    declare -i TEMP=$2
    declare -i TEMP2=0 

    while [ $TEMP -gt 0 ]
    do
        TEMP2="$TEMP%2"
        #printf "%d" "$TEMP2"
        ARRAY[$INDEX]=$TEMP2
        TEMP=$TEMP/2
        INDEX=$[ $INDEX + 1 ]  #note

    done

    for (( COUNT=INDEX; COUNT>-1; COUNT--)){

        printf "%d" "${ARRAY[$COUNT]}"  <<LINE 27
        #echo -n ${ARRAY[$COUNT]}       <<LINE 28
    }
fi
 }

why is this code giving this error

q5.sh: line 27: ARRAY[$COUNT]: unbound variable

same error comes with line 28 if uncommented

One more question, I am confused with the difference b/w '' and "" used in bash scripting any link to some nice article will be helpfull.

Upvotes: 2

Views: 172

Answers (1)

Dennis Williamson
Dennis Williamson

Reputation: 360133

It works fine for me except that you can't do return -1. The usual error value is 1.

The error message is because you have set -u and you're starting your for loop at INDEX instead of INDEX-1 (${ARRAY[INDEX]} will always be empty because of the way your while loop is written). Since you're using %d in your printf statement, empty variables will print as "0" (if set -u is not in effect).

Also, it's meaningless to declare an array with a size. Arrays in Bash are completely dynamic.

I would code the for loop with a test for 0 (because the -1 looks confusing since it can't be the index of an numerically indexed array):

for (( COUNT=INDEX - 1; COUNT>=0; COUNT--))

This form is deprecated:

INDEX=$[ $INDEX + 1 ]

Use this instead:

INDEX=$(( $INDEX + 1 ))

or this:

((INDEX++))

I also recommend using lower case or mixed case variables as a habit to reduce the chance of variable name collision with shell variables.

You're not using $1 for anything.

Upvotes: 1

Related Questions