Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash evaluation of expression .[].[]

Tags:

bash

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?

like image 650
Halle Knast Avatar asked Jun 27 '19 14:06

Halle Knast


People also ask

How do you evaluate an expression in shell scripting?

You can use expr utility to evaluate expressions in both of the command line or shell script. This may not be the best way to find out if it is Friday, but it seems to work. It's more of an exercise in xargs.

What is $() in bash?

$() means: "first evaluate this, and then evaluate the rest of the line". Ex : echo $(pwd)/myFile.txt. will be interpreted as echo /my/path/myFile.txt. On the other hand ${} expands a variable.

What is expression in bash?

Bash expression is the combination of operators, features, or values used to form a bash conditional statement. Conditional expression could be binary or unary expression which involves numeric, string or any commands whose return status is zero when success.


1 Answers

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 .[].[]  # .. .[ .]
like image 166
choroba Avatar answered Nov 16 '22 02:11

choroba