0

I have a pattern to replace in a bash script, and it replaces correctly if I run directly in terminal. But if I put the exact same code in a script it doesn't work.

Example:

test="1[[ 23 ]]4" && echo "${test//[[][[]*( )23*( )[]][]]/56}"

The above command outputs 1564 if I run in terminal, but it outputs 1[[ 23 ]]4 if I run in a script (I just create an empty script, put a bash shebang, paste the above code, add execute permission and run; I tried running with ./test.sh and also with bash ./test.sh to make sure bash is the shell used, but still the same result).

It works if I change the code to:

test="1[[ 23 ]]4" && echo "${test//[[][[] 23 []][]]/56}"

but I want 0 or more spaces, so the 1st would be the correct choice, but for some reason it's not working in a script.

I think it might be related to glob expansion working differently in the terminal and in a script, but I don't know how to proceed. I read the docs, but still no clue.

0

1 Answer 1

1

You need to turn on bash's extended globbing in the script (I think it's turned on automatically in interactive sessions, or maybe in your ~/.profile) in order for *() constructs to work right:

#!/usr/bin/env bash
shopt -s extglob
test="1[[ 23 ]]4" && echo "${test//[[][[]*( )23*( )[]][]]/56}"
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it worked! The funny thing is that I suspected it was about glob expansion and tried both shopt -s nullglob (I think this would cancel all glob expansion) and shopt -s globstar, but haven't tried shopt -s extglob.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.