Search code examples
shellunixshsolarisbitwise-operators

Are bitwise operators supported in regular shell /bin/sh (not bash)


I am getting errors in using bitwise & operators in /bin/sh. I can make it work in bash, but the script which will execute the code starts in regular shell, so I need to make it work in plain regular shell. I need to simply check if a certain bit is set e.g. 7th bit

Following code work in bash, but not in /bin/sh

#!/bin/bash
y=93
if [ $((($y & 0x40) != 0)) ]; then
  echo bit 7 is set
fi

I tried above in /bin/sh by removing arithmatic expansion

#!/bin/sh
y=93
val=`expr $y & 0x40`
if [ $val != 0 ]; then
   echo worked 1
fi

Can someone suggest how bitwise operator can be use in plain regular shell?


Solution

  • You can use division and modulo operations to check for a particular bit:

    if [ `expr \( $y / 64 \) % 2` -eq 1 ]; then
      echo bit 6 is set
    fi