2

I have an array, index is the hard drive size and value is number of hard drives having same size. So this is what i do.

DRIVE_SIZES[$DRIVE_SIZE]=`expr ${DRIVE_SIZES[$DRIVE_SIZE]} + 1`

I have not initialized the DRIVE_SIZES array to 0. So above line might not work. I would like to initialize a sparse array in bash script.

Lets say all drives in the host are of the same size, except one. Some 10 drives are of size 468851544 and one drive is of size 268851544. So I cannot initialize all index from 0-468851544 because I dont know the maximum disk size beforehand.

So is there a way to initialize such an sparse array to 0. May be if there is way to declare an integer array in bash that might help. But after some initial research found out I can declare an integer, but not integer array(might be wrong on this). Can someone help me with this ?

I read this, but this might not be the solution to me

3 Answers 3

2

Use increment in an arithmetic expression:

(( ++DRIVE_SIZES[DRIVE_SIZE] ))
Sign up to request clarification or add additional context in comments.

Comments

1

You can use parameter substitution to put a zero into the expression when the array key has not been defined yet:

DRIVE_SIZES[$DRIVE_SIZE]=`expr ${DRIVE_SIZES[$DRIVE_SIZE]:-0} + 1`

N.B. this is untested, but should be possible.

Comments

1

An array element when unset and used in arithmetic expressions inside (( )) and $(( )) has a default value of 0 so an expression like this would work:

(( DRIVE_SIZES[DRIVE_SIZE] = DRIVE_SIZES[DRIVE_SIZE] + 1 ))

Or

(( DRIVE_SIZES[DRIVE_SIZE] += 1 ))

Or

(( ++DRIVE_SIZES[DRIVE_SIZE] ))

However when used outside (( )) or $(( )), it would still expand to an empty message:

echo ${DRIVE_SIZES[RANDOM]} shows "" if RANDOM turns out to be an index of an element that is unset.

You can however use $(( )) always to get the proper presentation:

echo "$(( DRIVE_SIZES[RANDOM] ))" would return either 0 or the value of an existing element, but not an empty string.

Using -i to declare, typeset or local when declaring arrays or simple variables might also help since it would only allow those parameters to have integral values, and the assignment is always done as if it's being assigned inside (( )) or $(( )).

declare -i VAR
A='1 + 2'

is the same as (( A = 1 + 2 )).

And with (( B = 1 )), A='B + 1' sets A to 2.

For arrays, you can set them as integral types with -a:

declare -a -i ARRAYVAR

So a solution is to just use an empty array variable and that would be enough:

ARRAYVAR=()

Or

declare -a -i ARRAYVAR=()

Just make sure you always use it inside (( )) or $(( )).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.