[shell] mod, div ?!!

Solved
sassoura Posted messages 21 Registration date   Status Membre 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 réponse

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
mamiemando Posted messages 33541 Registration date   Status Modérateur Last intervention   7 933
 
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
sassoura Posted messages 21 Registration date   Status Membre Last intervention  
 
it's the bash interpreter... okay thanks :)
0
mamiemando Posted messages 33541 Registration date   Status Modérateur Last intervention   7 933
 
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
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
mamiemando Posted messages 33541 Registration date   Status Modérateur Last intervention   7 933
 
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