0

My script is

#! /bin/bash
  
v1="hello"
v2="world1"
subIndex=`expr index "${v1}" "${v2}"`
echo $subIndex

and I got the error of "expr: syntax error"

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Qiang Yao
  • 165
  • 12
  • Could you post _full_ error message verbatim? It's it `expr: syntax error: something something`? And check for dos line endings. – KamilCuk Jan 04 '21 at 23:19
  • @KamilCuk No, the BSD expr(1) on, e.g., MacOS 10.15.7 does not have `: something something`. –  Jan 04 '21 at 23:24
  • @KamilCuk Correct, I am using 10.15.7. – Qiang Yao Jan 04 '21 at 23:27
  • Note that `expr` in general is best avoided in favor of using bash builtins -- as an external command it's expensive to run (requires forking off a subprocess), and its most-used functionality, arithmetic, is mooted by POSIX.2's inclusion of standard-defined arithmetic operators. One can get `expr index` with clever use of `BASH_REMATCH`, f/e. – Charles Duffy Jan 04 '21 at 23:50

1 Answers1

1

It looks like you're using a version of expr which doesn't have an index operator.

As you can see in the POSIX standard man page there's no index in the table of operators. The only mention of index in that document says that the behaviour is undefined. We can assume that the standardisation process saw that only some implementations supported index and some or all of the participants did not want to add the additional functionality.

Some other implementations contain additional functionality above and beyond what is specified in the standard. You'll need to install one of these implementations or change your code. GNU expr is one implementation that does have index, length, etc..