12

Is something like the following code possible within a shell script?

var1=0xA (0b1010)
if ( (var1 & 0x3) == 0x2 ){
    ...perform action...
}

Just to make my intentions 100% clear my desired action would be to check bits of var1 at 0x3 (0b0011) and make sure that it equals 0x2 (0b0010)

 0b1010
&0b0011
_______
 0b0010 == 0x2 (0b0010)
codeforester
  • 39,467
  • 16
  • 112
  • 140
Jens Petersen
  • 189
  • 2
  • 11

2 Answers2

7

Bit manipulation is supported in POSIX arithmetic expressions:

if [ $(( var1 & 0x3 )) -eq $(( 0x2 )) ]; then

However, it's a bit simpler use an arithmetic statement in bash:

if (( (var1 & 0x3) == 0x2 )); then
chepner
  • 497,756
  • 71
  • 530
  • 681
4

Yes, this is entirely possible:

#!/bin/bash

var1=0xA # (0b1010)
if (( (var1 & 0x3) == 0x2 ))
then
  echo "Match"
fi
that other guy
  • 116,971
  • 11
  • 170
  • 194