bash script yields a different result when sourced

Viewed 75

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
1 Answers

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)
Related