kwasbob
kwasbob

Reputation: 47

Negative number in bash shell scripting

I need some help with a bash mathematical expression script. I need the expression below to be a negative 2 to the power of 63 but I have tried all sorts of combinations from "", '', (()) and even keeping the positive value but multiplying it by -1 but I can't seem to get the syntax right.

Original expression:

kw=`expr 2^63 | bc`

gives me 9223372036854775808 (which is correct) but I need to get a -9223372036854775808.

I want to be able to do a kw=expr -2^63 | bc to get a negative results but it's not as straight-forward as I'd hoped. Hence my numerous attempts of different permutations to the expression.

Any help will be very appreciated.

Upvotes: 2

Views: 9436

Answers (2)

janos
janos

Reputation: 124704

Here you go:

$ kw=$(echo -2^63 | bc)
$ echo $kw
-9223372036854775808

UPDATE

@DigitalTrauma is right, if you're in bash, then using a bash here string is better (one less process, more efficient):

kw=$(bc <<< -2^63)

Upvotes: 4

Digital Trauma
Digital Trauma

Reputation: 16016

Since this is , you don't even need the echo; you can use a bash here string instead:

$ kw=$(bc <<< -2^63)
$ echo $kw
-9223372036854775808

Upvotes: 3

Related Questions