Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does an ampersand in arithmetic evaluation and numbers with x's mean in Bash?

Tags:

linux

bash

I'm curious about what exactly the following comparison does, in as much detail as possible, especially relating to the 0x2 and the & characters and what exactly they do,

if [ $((${nValid} & 0x1)) -eq 1 ]; then
  #...snip...
fi

if [ $((${nValid} & 0x2)) -eq 2 ]; then
  #...snip...
fi
like image 793
TJ L Avatar asked Sep 04 '25 16:09

TJ L


2 Answers

& is the bitwise AND operator. So you are asking to do a bitwise and between 0x1 and the value that ${nVAlid} is returning.

For more information on bitwise operations look here.

like image 184
dave Avatar answered Sep 07 '25 09:09

dave


A shell script interprets a number as decimal (base 10), unless that number has a special prefix or notation. A number preceded by a 0 is octal (base 8). A number preceded by 0x is hexadecimal (base 16). A number with an embedded # evaluates as BASE#NUMBER (with range and notational restrictions).

So, in [ $((${nValid} & 0x1)) -eq 1 ], $nValid is anded with 0x1 and compared with decimal 1. Similarly the second comparison too.

Read this and this for detailed info.

like image 40
pavanlimo Avatar answered Sep 07 '25 09:09

pavanlimo