'Why does "length" work in "expr" under Bash?
Here, $expr length "geekss" "<" 5 "|" 19 - 6 ">" 10 ouputs:
1
while, $expr length "geekss" "<" 5 "&" 19 - 6 ">" 10 outputs:
0
I am a bit confused about the deductions. How does length work under expr?
Solution 1:[1]
The difference between the two commands (assuming you're showing $ as your prompt and not as a variable expansion) is the change from | to &. The similarities in the two statements are:
length "geekss" < 5is false in both cases19 - 6 > 10is true in both cases
The change in output comes as a result of your change in logical tests:
|is an "OR", which evaluates to "ARG1 if it is neither null nor 0, otherwise ARG2"&is an "AND", which evaluates to "ARG1 if neither argument is null or 0, otherwise 0"
In your case, the | variation is evaluating to the truth of 19 - 6 > 10 while the & variation sees that length "geekss" < 5 is 0 (false) and so returns 0.
Solution 2:[2]
How does length work under expr?
It gets the length of the string geekss. The string geekss has 6 characters, so length "geekss" is 6.
The man expr page seems also to be clear:
length STRING
length of STRING
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jeff Schaller |
| Solution 2 | KamilCuk |
