From d36797bd0e85bed076f40ae3c9cae4ded9dd9d05 Mon Sep 17 00:00:00 2001 From: Vidar Holen Date: Tue, 8 Apr 2025 10:22:01 -0700 Subject: [PATCH] Created SC2331 (markdown) --- SC2331.md | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 SC2331.md diff --git a/SC2331.md b/SC2331.md new file mode 100644 index 0000000..eda843a --- /dev/null +++ b/SC2331.md @@ -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! \ No newline at end of file