You can use a bash
wrapper function to check for the bit set, defining a local IFS
operator either in a script or .bashrc
# Returns the bit positions set in the number for the given bit mask
# Use the return value of the function directly in a script
bitWiseAnd() {
local IFS='&'
printf "%s\n" "$(( $* ))"
}
and use it in a function as below in your script
# The arguments to this function should be used as number and bit-mask, i.e.
# bitWiseAnd <number> <bit-mask>
if [ $(bitWiseAnd "93" "0x40") -ne 0 ]
then
# other script actions go here
echo "Bit set"
fi
The idea is to use the Input-Field-Separator(IFS), a special variable in bash
used for word splitting after expansion and to split lines into words. The function changes the value locally to use word-splitting character as the bit-wise AND
operator &
.
Remember the IFS
is changed locally and does NOT take effect on the default IFS
behaviour outside the function scope. An excerpt from the man bash
page,
The shell treats each character of IFS as a delimiter, and splits the results of the other expansions into words on these characters. If IFS is unset, or its value is exactly , the default, then sequences of , , and at the beginning and end of the results of the previous expansions are ignored, and any sequence of IFS characters not at the beginning or end serves to delimit words.
The "$(( $* ))"
represents the list of arguments passed to be split by &
and later the calculated value is output using the printf
function. The function can be extended to add scope for other arithmetic operations also.