[shell] mod, div ?!!

Solved
sassoura Posted messages 21 Registration date   Status Member Last intervention   -  
 Anonymous user -
Hello,

How to write in shell the equivalent of the integer division operator (/ in C language) and modulo operator (% in C language) in bash?

Thank you :)

Configuration: Linux / Firefox 19.0

1 answer

  1. Anonymous user
     
    Hi,

    I understand that you want to perform arithmetic operations with the command interpreter (which one? sh? bash? ...)

    Modulo and division are expressed the same way as in C.

    echo $((2%3)) 2 echo $((2%2)) 0


    rtfm.
    2
    1. mamiemando Posted messages 33228 Registration date   Status Moderator Last intervention   7 944
       
      In fact, he posted it in the shell section, so I just understood his question (or at least I think so): how do you write in shell an integer division and a modulo.

      So you provided the answer in bash...

      In shell:

      (mando@silk) (~) $ expr 16 / 3 5 (mando@silk) (~) $ expr 16 % 3 1


      To store it in a shell variable:

      x=$(expr 16 / 3) echo $x


      Good luck
      1
    2. sassoura Posted messages 21 Registration date   Status Member Last intervention  
       
      it's the bash interpreter... okay thanks :)
      0
    3. mamiemando Posted messages 33228 Registration date   Status Moderator Last intervention   7 944
       
      So the problem is solved!

      Think, as someone starting with Q says, to take the time to do a Google search for such simple questions; normally, you should be able to find it yourself ;-)

      And especially try to ask your question more clearly next time! So I rewrote your initial message so that people who come across this thread better understand your question.

      Have a good evening ;-)
      0
    4. Anonymous user
       
      Hi mamiemando,

      expr is not a bash command.

      Shells that conform to the POSIX standard can evaluate arithmetic expressions on integers without resorting to external programs, as I demonstrated, within $(( )).
      0
    5. mamiemando Posted messages 33228 Registration date   Status Moderator Last intervention   7 944
       
      I thought the $(( )) operator was specific to bash, but I could be mistaken. I admit I don't often work with the shell...

      At the same time, expr is part of coreutils, which is just a "necessary" package under Debian, so well... external program is a strong term, I think you should have it everywhere :-) That said, if the syntax $((...)) works in any shell, it's more concise, more readable, and cleaner...
      0