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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With