bash: double vs single brackets in file test expression evaluation

bash, shell

Solution

Because that's how they work. `[[` is smarter than `test`, and should be used except where strict compatibility with `sh` is required.

Problem

I have a question about file test expressions in bash. Here is a simple script to illustrate my question: ``` set -x read -p "Enter a filename: " var1 if [ - e $var1 ] then echo file exists else echo file not found fi ``` There are three scenarios: - At the prompt, I enter `foo` , which is a file that exists in the directory from which I'm running the script. As expected, the output is `file exists` . - At the prompt, I enter `bar` . No such file exists in the directory from which I'm running the script. As expected, the output is `file not found` . - At the prompt, I hit `<enter>` without typing anything. Surprisingly, the output is `file exists` . If I use `if [[ -e $var1 ]]` , i.e., double brackets instead of single, the behavior is correct: even in the third case, I get `file not found`. I stuck a `set -x` at the top of the file to see what was going on. With single brackets, the variable is evaluated as: `'[' -e ']'` . With double, it is evaluated as `[[ -e '' ]]` . This is interesting. Why is the expression being evaluated differently in the two cases? I would be grateful for an explanation. Sorry if I'm missing the obvious. Thanks!

Original source