Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 854
YS_NE Avatar asked Nov 20 '25 08:11

YS_NE


2 Answers

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
like image 90
Alnitak Avatar answered Nov 22 '25 23:11

Alnitak


I think the problem is that you're using the string returned by your arithmetic expansion, and not the exit code. You probably should do the test for equal to 0 on the outside like

if [ "$((y & 0x40))" -ne 0 ]; then

otherwise $(((y & 0x40) != 0)) is returning a string, and it will always be non-empty so the truth test will always pass.

like image 41
Eric Renouf Avatar answered Nov 22 '25 22:11

Eric Renouf