Get the App
SLTechnology News&Howtos  ›  Servers  › 

How to understand the logical sum (& ) in Bash

Shulou Source: shulou.com Published: 2022-05-31 13:50:47 10月04日 Update

This article shows you how to understand the logic and (&) in Bash. The content is concise and easy to understand. It will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

In Bash, you can use & as the AND (logical sum) operator.

Some people may think that the meaning of the two articles is similar, but it is not. Although the first article discussed how to use & at the end of the command to run the command in the background, and then dissected process management, the second article saw & as a way to reference file descriptors, which let us know. When used in combination, you can direct input or output somewhere else.

But we haven't touched the & which is used as an AND operator. So, let's take a look.

& is a bitwise operator

If you are familiar with binary number manipulation, you must have heard of AND and OR. These are bitwise operations that operate on the bits of a binary number. In Bash, use & as the AND operator and | as the OR operator:

AND:

0 & 0 = 00 & 1 = 01 & 0 = 01 & 1 = 1

OR:

0 | 0 = 00 | 1 = 11 | 0 = 11 | 1 = 1

You can AND any two numbers and use echo to output the results:

$echo $((2 & 3)) # 00000010 AND 00000011 = 000000102$ echo $((120 & 97)) # 01111000 AND 01100001 = 0110000096

The same is true of OR (|):

$echo $((2 | 3)) # 00000010 OR 00000011 = 000000113$ echo $((120 | 97)) # 01111000 OR 01100001 = 01111001121

Description:

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

Use ((...)) to tell Bash that the content between the parentheses is some kind of arithmetic or logical operation. ((2 + 2)), ((5% 2)) (% is the modularization operator) and ((5% 2) + 1) (equal to 3) all work.

Like a variable, use $to extract the value so that you can use it.

Spaces have no effect: (2-3) is equivalent to (2-3) and (2-3).

Bash can only operate on integers. Try doing this: ((5 / 2)), you will get 2; or this ((2.5 & 7)), but you will get an error. Then, using anything but integers in bitwise operations (which is what we're talking about now) is usually something you shouldn't do.

Tip: if you want to see what decimal numbers look like in binary, you can use bc, a command-line calculator pre-installed with most Linux distributions. For example:

Bc

Tags: Commands runs numbers logic operations variables operators articles errors content meaning output two binary articles results things places that is operators Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi MariaDB Apple Redmi Huawei