Home > Back-end >  Why does "length" work in "expr" under Bash?
Why does "length" work in "expr" under Bash?

Time:03-19

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?

CodePudding user response:

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" < 5 is false in both cases
  • 19 - 6 > 10 is 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.

CodePudding user response:

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
  •  Tags:  
  • bash
  • Related