Carmageddon
Carmageddon

Reputation: 2839

Bash Division and Modulus

I have a problem getting the following (tried multiple varians with $, (), backticks `, etc...) to work:

GetAmountOfFileBlocks()
{
        export DOC_BLOCKS=0
        DOC_BLOCKS= $(`expr $DOCS_AMOUNT / $CHUNK_AMOUNT`)
        DIVISOR=echo expr  $DOCS_AMOUNT % $CHUNK_AMOUNT
        if [ $DIVISOR -ne "0" ]
        then
                $DOC_BLOCKS=$DOC_BLOCKS+1;
        fi
}

In debug (with -x) it shows as something like this:

  • export DOC_BLOCKS=0
  • DOC_BLOCKS=0 ++ expr 193 / 64
  • DOC_BLOCKS=
  • 3 ./cnv_dm_assign_files_to_chunks.sh: line 87: 3: command not found
  • DIVISOR=echo
  • expr 193 % 64

I need to get a number that would represent the number of blocks needed to accomodate the given divisor (in this example, 193/64 would mean 3 and a reminder, meaning I need 4 "blocks" for my purposes.

Upvotes: 1

Views: 316

Answers (1)

Sean Bright
Sean Bright

Reputation: 120654

Something like this should work:

DOC_BLOCKS=$(( DOCS_AMOUNT / CHUNK_AMOUNT ))
REMAINDER=$(( DOCS_AMOUNT % CHUNK_AMOUNT ))

if [ "$REMAINDER" -gt "0" ]
then
  DOC_BLOCKS=$(( DOC_BLOCKS + 1 ))
fi

Upvotes: 4

Related Questions