Bash: double vs single brackets in file expression evaluation

I have a question about expressing test files 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 command prompt, enter foo , which is the file that exists in the directory from which I am running the script. As expected, the output of file exists .
  • At the command prompt, enter bar . There is no such file in the directory from which I am running the script. As expected, the output is file not found .
  • At the command prompt, I pressed <enter> without typing anything. Surprisingly, the output of file exists .

If I use if [[ -e $var1 ]] , i.e. double brackets instead of single brackets, the behavior is correct: even in the third case, I get file not found .

I stuck set -x at the top of the file to find out what was going on. In separate brackets, the variable is evaluated as: '[' -e ']' . With a double, it is rated as [[ -e '' ]] . It is interesting. Why is the expression evaluated differently in these two cases?

I would be grateful for the explanation. Sorry if I miss the obvious. Thanks!

+6
source share
2 answers

Because they work. [[ smarter than test , and should be used unless strict compliance with sh is required.

+3
source

change to if [ -e "$var1" ]

Read more about [] and [[ ]] Here

+6
source

Source: https://habr.com/ru/post/914396/


All Articles