Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

My non-interactive bash shell has extglob off. I would like to turn it on in the statement immediately before a command, but I have noticed that when shopt -s extglob is within an if .. then .. else block, it somehow does not register.

The following extglob-dependant command is not valid: syntax error near unexpected token '('.

Where can extglob be set, and why is there a restriction, at all? Does this apply to other options? ... GNU bash 4.1.5

This works:

shopt -s extglob
if true ;then
    touch a.bcd; ls a.@(bcd)
fi

This fails:

if true ;then
    shopt -s extglob
    touch a.bcd; ls a.@(bcd)
fi
... line 17: syntax error near unexpected token `('
... line 17: `touch a.bcd; ls a.@(bcd)' 
share|improve this question
add comment

1 Answer

up vote 4 down vote accepted

Not sure if there is a more authoritative source (ie. man page / official documentation) on this issue, but I found a site which explains this behavior: http://mywiki.wooledge.org/glob

Because the extglob option changes the way certain characters are parsed, it is necessary to have a newline (not just a semicolon) between the shopt command and any subsequent commands that use extended globs. Likewise, you cannot put shopt -s extglob inside a statement block that uses extended globs, because the block as a whole must be parsed when it's defined; the shopt command won't take effect until the block is evaluated, at which point it's too late. In fact as bash parses the entire statement block before evaluating any of it, you need to set extglob outside of the outermost block.

share|improve this answer
1  
Thanks. The wooledge link covers it quite well. I suppoes it had to be impemented that way because of some legacy issues. –  Peter.O Aug 21 '12 at 18:12
    
@Peter.O I would say that it's that way because bash's parser is wonky. Of course, I'm a dirty-mouthed zsh user, except that I seem to remember this is the official reason given on the bash mailing list. Bash has a lot of similar parsing issues, such as alias e=echo; e hello not working: the alias definition only takes place on the next newline. –  Gilles Aug 21 '12 at 23:18
    
That's interesting, thanks... One day, I'll get around ot looking at zsh. It seems to have all the bells and whistles; very compact ones. –  Peter.O Aug 22 '12 at 8:04
add comment

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.