2

I'm very new to bash and I'm trying to extract a portion of a string based on a pattern, but when I execute my code I'm seeing errors.

Sample code:

#!/bin/sh

STRING="LAX-8912_Words_Are_Here";

if [[ $STRING =~ LAX-(\d)+ ]]; then
    echo "${BASH_REMATCH[1]}"
fi

So from the code above, I'm wanting to extract the "LAX-8912" portion of the string. Basically the string will be LAX- and then a series of numbers, could be any length. When the code is exectued however, I'm getting this message:

Syntax error: "(" unexpected (expecting "then")

I've also tried storing the regex in a variable like this:

#!/bin/sh

STRING="LAX-8912_Words_Are_Here";
REX="LAX-(\d)+";

if [[ $STRING =~ $REX ]]; then
    echo "${BASH_REMATCH[1]}"
fi

But then I get this error:

 [[: not found

My bash version is 4.2.25 so I'm guessing it's not a version issue, but I'm at a bit of a loss as to what's going.

1 Answer 1

4

Since your script starts with:

#!/bin/sh

it will run the system shell, which may be a completely different shell like dash, or at best bash in compatibility mode. You should use:

#!/bin/bash

to use bash with all its features.

Similarly, if run with sh file you override the shebang and force the script to run with the system shell. Use ./file so that the script can run with its declared shebang.

Sign up to request clarification or add additional context in comments.

1 Comment

Oh man, how embarrassing, thank you very much for that. My regex appears to be wrong but at least now I can see the output. Thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.