bisgardo
bisgardo

Reputation: 4600

Bash evaluation of expression .[].[]

Consider the following expression evaluations:

$ echo .
.
$ echo .[]
.[]
$ echo .[].
.[].
$ echo .[].[]
..                # <- WAT??
$ echo .[].[].
.[].[].
$ echo .[].[].[]
.[].[].[]

Can someone explain why .[].[] has this special behavior?

(Tested in bash 3.2.57(1)-release (x86_64-apple-darwin18) and 4.4.23(1)-release (arm-unknown-linux-androideabi).

I suspect it has something to do with .. being a valid "file" (the parent directory). But then why doesn't e.g. .[]. produce the same result?

Upvotes: 11

Views: 73

Answers (1)

choroba
choroba

Reputation: 241768

That's because [] creates a character class. Normally, ] must be escaped (backslashed) to be included in the class, but you don't have to escape it if it immediately follows the opening bracket. Therefore, [].[] in fact means [\].[] which matches any of the characters ., ], and [.

You can verify it by creating files named .] and .[.

touch .\[ .\]
echo .[].[]  # .. .[ .]

Upvotes: 10

Related Questions