6

Could you help me, why this script works when sourced (or even directly on console) and does not work on a script?

I have checked and in any case I'm using the same bash in /bin/ and always 4.4.19(1)-release (checked with $BASH_VERSION).

Moreover I tried removing shebang but nothing changes.

#!/bin/bash

fname=c8_m81l_55.fit
bname=${fname%%+(_)+([0-9]).fit}
echo $bname

GIving these results:

test:~$ ./test.sh
c8_m81l_55.fit
test:~$ . ./test.sh
c8_m81l
0

1 Answer 1

6

Bash does not recognize +(pattern) syntax unless extglobs are enabled, and they are disabled by default. Apparently your bash setup enables them in interactive sessions; that's why your script works only when sourced in an interactive shell.

To fix that, either enable extglobs within the script by this command:

shopt -s extglob

Or use an alternative that works irrespective of shell's interactiveness:

bname=$(sed 's/__*[0-9][0-9]*\.fit$//' <<< $fname)
# with GNU sed it'd look like:
bname=$(sed -E 's/_+[0-9]+\.fit$//' <<< $fname)
Sign up to request clarification or add additional context in comments.

Comments

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.