What is $((x|y)) ?


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting What is $((x|y)) ?
# 1  
Old 11-07-2012
What is $((x|y)) ?

I'm analyzing a few scripts we have here, and what I often see in combination with return values is $((x|y)) and I can't figure out how it works and why it's used. Can anyone explain this to me? Thanks!

Code:
$ echo $((1|1))
1
$ echo $((1|2))
3
$ echo $((1|3))
3
$ echo $((1|4))
5

# 2  
Old 11-07-2012
This User Gave Thanks to bartus11 For This Post:
# 3  
Old 11-07-2012
The double bracket is used in bash for arithmetic expansions. thus $((x|y)) is a bitwise OR of the numeric values in $x and $y
This User Gave Thanks to Skrynesaver For This Post:
# 4  
Old 11-07-2012
Thanks, makes sense now. Still don't completely understand the use of it though. If for example you have a script like this:

Code:
retval=0
command1
retval=$(($?|$retval))

command2
retval=$(($?|$retval))

return $retval

# 5  
Old 11-07-2012
Well, it could tell you if, for example, either function returns an error:

Code:
$ cat myScript
Func1() {
  return $1
}

Func1 1
retval=$?
Func1 0
echo $(($?|$retval))

Func1 0
retval=$?
Func1 0
echo $(($?|$retval))

Func1 1
retval=$?
Func1 1
echo $(($?|$retval))

$ ./myScript
1
0
1

Bitwize OR is useful for bitfields to set specific bits, for example where you represent X number of on-off options, in the same, X number, of bits, you can use a bitwize or to test if a specific option is set.
This User Gave Thanks to Scott For This Post:
# 6  
Old 11-07-2012
I see.. Thanks Scott, starting to understand the use of it Smilie
# 7  
Old 11-07-2012
Quote:
Originally Posted by Subbeh
Thanks, makes sense now. Still don't completely understand the use of it though.
It is bitwise arithmetic, not often needed in shell(which deals with mostly strings). It transforms numbers in a raw binary way.
Login or Register to Ask a Question

Previous Thread | Next Thread
Login or Register to Ask a Question