Bash Files – Difference Between `if [ -a FILE ]` and `if [ -e FILE ]`


I only want to check in bash if a certain FILE exists.
On this page two options are mentioned to use with if:

  • [ -a FILE ] – True if FILE exists
  • [ -e FILE ] – True if FILE exists

Are they equivalent or is there any difference between them?

Best Answer

What does -a do and why does it exist ?

The -a option is the same thing as -e, and exists for compatibility with Korn Shell from which Bash borrowed a lot of features.

From POSIX standard, description of test command(link):

An early proposal used the KornShell -a primary (with the same meaning), but this was changed to -e because there were concerns about the high probability of humans confusing the -a primary with the -a binary operator.

side note: binary means flag that appears between two variables [ $var1 -a $var2 ], primary means appearing in the list of arguments first as in [ -a $var ]

In fact, Korn Shell (ksh93 here) manual states:

-a file

Same as -e below. This is obsolete.

The test command that is used in the TLDP article you referenced uses bash built-in test , however the option is also present in /usr/bin/test despite missing from documentation:

$ /usr/bin/test -a /etc/passwd  && echo 1                                   

If functionality is the same, is it good idea to use it?

So long as you are 100% sure your scripts will be used on either Bash or Korn Shell - then yes, it is alright. However, if you strive for portability of your scripts and want to write script the Right WayTM, you should use -e. The standard Ubuntu shell, /bin/sh, which is actually Dash - Debian Amquist Shell - doesn't recognize that as valid option:

$ dash
$ test -a /etc/passwd
dash: 1: test: -a: unexpected operator

In cases where you want to port your script to other platforms, using -a is not guaranteed to be safe with /usr/bin/test as well, and you should stick with -e because it is in fact specified by POSIX standard.