mirror of
https://github.com/koalaman/shellcheck.git
synced 2025-10-03 19:29:44 +08:00
Created SC2331 (markdown)
34
SC2331.md
Normal file
34
SC2331.md
Normal file
@@ -0,0 +1,34 @@
|
||||
## For file existence, prefer standard -e over legacy -a.
|
||||
|
||||
### Problematic code:
|
||||
|
||||
```sh
|
||||
if [ -a ~/.bash_aliases ]
|
||||
then
|
||||
source ~/.bash_aliases
|
||||
fi
|
||||
```
|
||||
|
||||
### Correct code:
|
||||
|
||||
```sh
|
||||
if [ -e ~/.bash_aliases ]
|
||||
then
|
||||
source ~/.bash_aliases
|
||||
fi
|
||||
```
|
||||
### Rationale:
|
||||
|
||||
The POSIX standard way to check whether a file exists is `[ -e file ]`.
|
||||
|
||||
Bash and Ksh have historically allowed using `-a`, but this has no benefit and some potential downsides. For example, in Bash `[ -a file ]` is true when the file exists, but `[ ! -a file ]` is also true, and unconditionally so, because `-a` is treated as logical "and" between non-empty strings.
|
||||
|
||||
Avoid the ambiguity entirely by always using the standard, portable `-e`.
|
||||
|
||||
### Exceptions:
|
||||
|
||||
None
|
||||
|
||||
### Related resources:
|
||||
|
||||
* Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!
|
Reference in New Issue
Block a user