I am practicing with parameter substitution in bash.

I wrote the following dummy script:

#!/bin/bash

var1="/some/path/to/file/the_file.arbitrary.n.ext.0.random.ext"
var2="/some/path/to/file/the_file.arbitrary.n.ext.0.ext"

pattern='.[0-9]?(.random).ext'

echo "${pattern}"
echo "${var1/${pattern}/}"
echo "${var2/${pattern}/}"

Basically, the pattern is meant to strip off the last part of the file name.


Executing the dummy script results in:

~$ ./dummy.sh 
.[0-9]?(.random).ext
/some/path/to/file/the_file.arbitrary.n.ext.0.random.ext
/some/path/to/file/the_file.arbitrary.n.ext.0.ext

whereas evaling the script's contents or, equivalently, the direct input of that sequence of commands in the interactive shell, results in:

~$ eval "$(cat dummy.sh)"
.[0-9]?(.random).ext
/some/path/to/file/the_file.arbitrary.n.ext
/some/path/to/file/the_file.arbitrary.n.ext

The pattern '.[0-9]*.ext' works, so the issue clearly is confined to the sub-string '?(.random)'. The issue could be with ?, since it is a reserved character in the context of parameter substitution. However, if that were the issue, I would expect the pattern to either fail or succeed the same in both cases.

Where's the probably obvious pitfall?

share|improve this question
up vote 9 down vote accepted

The problem may be that the extglob shell option is set in the interactive shell, but not in the script shell.

$ shopt -u extglob
$ echo "${var1/${pattern}/}"
/some/path/to/file/the_file.arbitrary.n.ext.0.random.ext
$ shopt -s extglob
$ echo "${var1/${pattern}/}"
/some/path/to/file/the_file.arbitrary.n.ext

So you can try putting shopt -s extglob right after the shebang line in the script.

From the Bash Reference Manual:

If the extglob shell option is enabled using the shopt builtin, several extended pattern matching operators are recognized.... Composite patterns may be formed using one or more of the following sub-patterns:

?(PATTERN-LIST)
    Matches zero or one occurrence of the given patterns.

share|improve this answer
    
'back to the basics', indeed. Thank you, I completely overlooked that detail. – Patrick Trentin 15 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.