Yogi Yogi - 3 months ago 30
Bash Question

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

if [ $((($y & 0x40) != 0)) ]; then
echo bit 7 is set

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

val=`expr $y & 0x40`
if [ $val != 0 ]; then
echo worked 1

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


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