Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash script yields a different result when sourced

Tags:

bash

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
like image 934
Alessio Carlini Avatar asked Apr 10 '20 07:04

Alessio Carlini


People also ask

What does $@ do in bash script?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.

What does ${ 1 mean in bash script?

- 1 means the first parameter passed to the function ( $1 or ${1} ) - # means the index of $1 , which, since $1 is an associative array, makes # the keys of $1.

What is $s in bash?

From man bash : -s If the -s option is present, or if no arguments remain after option processing, then commands are read from the standard input. This option allows the positional parameters to be set when invoking an interactive shell. From help set : -e Exit immediately if a command exits with a non-zero status.

What is $Bash_source?

BASH_SOURCE. An array variable whose members are the source filenames where the corresponding shell function names in the FUNCNAME array variable are defined. The shell function ${FUNCNAME[$i]} is defined in the file ${BASH_SOURCE[$i]} and called from ${BASH_SOURCE[$i+1]} BASH_SUBSHELL.


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)
like image 182
oguz ismail Avatar answered Oct 13 '22 17:10

oguz ismail