From c5c5da566ec812b107a72662a0b7fa8dea9f5e22 Mon Sep 17 00:00:00 2001 From: wileyhy <84648683+wileyhy@users.noreply.github.com> Date: Sun, 6 Oct 2024 01:44:33 -0700 Subject: [PATCH] Update content of section, "Rationale." --- SC1014.md | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/SC1014.md b/SC1014.md index 88976da..08c103a 100644 --- a/SC1014.md +++ b/SC1014.md @@ -16,15 +16,20 @@ if grep -q pattern file then echo "Found a match" fi - ``` + + ### Rationale: -`[ .. ]` is not part of shell syntax like `if` statements. It is not equivalent to parentheses in C-like languages, `if (foo) { bar; }`, and should not be wrapped around commands to test. +`[ ... ]` as shell syntax is a simple command that tests for whether certain conditions are true or false, such as whether the value assigned to a variable has a non-zero length (`[ -n "${foo}" ]`) or whether a file system object is a directory (`[ -d "${dir}" ]`). `If-then-(elif-then)-else-fi` statements are logical constructs which themselves contain lists of commands which can include simple commands. -`[` is just regular command, like `whoami` or `grep`, but with a funny name (see `ls -l /bin/[`). It's a shorthand for `test`. +`[` is just regular command, like `whoami` or `grep`, but with a funny name (see `ls -l /bin/[`). It's a shorthand for `test`. `[[` is similar to both `[` and `test`, but `[[` offers some additional unary operators, such as '=~' the regular expression comparison operator. It allows one to use extglobs such as `@(foo|bar)` (a "bashism"), among some other less commonly used features. -If you want to check the exit status of a certain command, use that command directly as demonstrated in the correct code. +`[[`, `[` and `test` are often used within `if...fi` constructs in the conditional commands position: which is between the 'if' and the 'then.' + +There are certain shell syntaxes which can be wrapped directly around simple commands, in particular: (1) `{ ...;}` compound command groupings, (2) `$( ... )` command substitutions and (3) `<( ... )` and `>( ... )` process substitutions. Some examples include `{ [ -d "${HOME}/file" ]; echo $?;}`, `var=$(logname)` and `readarray -d "" -t files < <( find ~ -iname '*bash*' -print0 2> /dev/null )`, respectively. However, the various testing commands' syntaxes are not to be included among this list. + +If you want to check the exit status of a certain command, use that command directly as demonstrated in the correct code, above. If you want to check the output of a command, use `"$(..)"` to get its output, and then use `test` or `[`/`[[` to do a string comparison: