Chris
Chris

Reputation: 13

11*(...) as a bash parameter without quotation marks

I'm trying to write a small piece of code that passes a small formula to another program, however i've found that something strange happens when the formula starts with 11*(:

$ echo 11*15

Neatly prints '11*15'

$ echo 21*(15)

Neatly prints '21*(15)', while

echo 11*(15)

Only gives '11'. As far as I've found this only happens with '11*('. I know that this can be solved by using proper quotation marks, but I'm still curious as to why this happens.

Does anyone know?

Upvotes: 1

Views: 125

Answers (2)

Keith Thompson
Keith Thompson

Reputation: 263237

11*(15) uses a Bash-specific extended glob syntax. You've stumbled across it accidentally, emphasizing why quotation marks are a good idea. (I also learned a lot tracking down why it was working differently for me; thanks for that.)

The behavior of

echo 11*(15)

in bash is going to vary depending on whether extglob is enabled. If it's enabled *(PATTERN-LIST) matches zero or more occurrences of the patterns. If it's disabled, it doesn't, and the resulting ( is likely to cause a syntax error.

For example:

$ ls
11  115  1155  11555  115555
$ shopt -u extglob
$ echo 11*(55)
bash: syntax error near unexpected token `('
$ shopt -s extglob
$ echo 11*(55)
11 1155 115555
$

(This explains the odd behavior I discussed in comments.)

Quoting from the bash 4.2.8 documentation (info bash):

If the `extglob' shell option is enabled using the `shopt' builtin, several extended pattern matching operators are recognized. In the following description, a PATTERN-LIST is a list of one or more patterns separated by a `|'. 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.

`*(PATTERN-LIST)' Matches zero or more occurrences of the given patterns.

`+(PATTERN-LIST)' Matches one or more occurrences of the given patterns.

`@(PATTERN-LIST)' Matches one of the given patterns.

`!(PATTERN-LIST)' Matches anything except one of the given patterns.

Upvotes: 0

ghostdog74
ghostdog74

Reputation: 342333

How is your program coded? If its coded to take in parameters, then pass your formula like

./myprogram "11*15"

or

echo '11*15' | myprogram

If you do echo just like that on the command line, you may inadvertently display files that has 11 in its file name

Upvotes: 1

Related Questions