0

I am trying to do the following thing the bash shell. Plz tell me how can I do this ?

  ramsize=4002
  ramsize=ramsize/1000
1
  • It is a bit unclear what you want to store in $ramsize: the integer division (4) or the float division (4.002)? Commented Aug 7, 2014 at 10:09

3 Answers 3

2

You can use this:

$ v=2000
$ (( v/=1000 ))
$ echo $v
2

In your case:

$ ramsize=4002
$ (( ramsize/=1000 ))
$ echo $ramsize
4
Sign up to request clarification or add additional context in comments.

Comments

1

You can use expr Like this :

  $ SIZE="4002"
  $ DIV=$(expr "$SIZE" / "1000" )
  $ MOD=$(expr "$SIZE" % "1000" )
  $ echo $DIV
  4
  $ echo $MOD
  2

back to your example:

 $ ramsize=4002
 $ ramsize=$( expr "$ramsize" / "1000" )                    //ramsize = 4

Update the last statement according to konsolebox comment ,

the last line before modification :

$ ramsize=$("$ramsize" / "1000" )

the last line after modification :

$ ramsize=$(expr "$ramsize" / "1000" )

5 Comments

* ramsize=$(("$ramsize" / "1000" )). And (( ramsize = ramsize / 1000 )) is more efficient, especially (( ramsize /= 1000 )).
* ramsize=$(( $ramsize / 1000 )) it doesn't works when you quote vars see Arithmetic Expansion, i think C-style (()) for loops aren't POSIX , can you please explain to me why c style is more efficient?
Probably because everything (calculations and assignments) occur in a single scope. With ramsize=$(( $ramsize / 1000 )), $(()) would still pass the expanded value to the function that assigns the value to $ramsize.
Actually i didnt see that i forgot expr, and with your comment i realized that there is something wrong :)
expr is essentially obsolete for arithmetic, as all of its functions (other than regular-expression matching) have been incorporated into the POSIX shell via the $((...)) expression.
1

With floats:

ramsize=4002
ramsize=$(echo "scale=4; $ramsize / 1000" | bc)
echo "$ramsize"  ## Outputs 4.0020

1 Comment

Hot to do the following ramsize=16000 freesize=3000 cachesize=8 ramsize=ramsize/1000 cachesize=freesize/1000

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.