Updated SC2230 (markdown)

Mingye Wang
2019-12-25 16:37:57 +08:00
parent 7730b9706a
commit e349e43dea

@@ -11,7 +11,11 @@ which grep
### Correct code:
```sh
# For the path of a single, unaliased, external command,
# or to check whether this will just "run" in this shell:
command -v grep
# To check whether commands exist, without obtaining a reusable path:
hash grep
```
### Rationale:
@@ -24,7 +28,9 @@ This check is opt-in only in 0.7.1+, and you may choose to [[ignore]] it in earl
### Caveats:
With BASH 5.0.7 (via homebrew on macOS 10.13.6), `command -v` appears to take multiple parameters:
#### `command -v` does not check ALL parameters
`command -v` succeeds (with exit code 0) if *any* command exists:
```
# grep is in /usr/bin/grep
@@ -34,9 +40,9 @@ $ command -v -- grep foobar; echo $?
0
```
but succeeds (with exit code 0) if *any* command exists. In the above
example, it should have failed and exited with 1 unless *all* commands
exist.
In the above example, it should have failed and exited with 1 unless *all* commands
exist, if it were to be a replacement for `which`. Other problems associated with
`command` include its inclusion of builtins, aliases, and functions.
An alternative is:
@@ -46,6 +52,11 @@ $ hash <file1> <file2>
Which observes the standard behaviour of failures.
To obtain a path, `type -p` can be used instead. Like `command -v`, it has a similarly
quirky behavior with builtins, aliases, and functions, although this is
arguably milder since it would print nothing for these cases. The failure condition is
similar to `hash`.
### Related resources:
* [Check if a program exists from a Bash script](https://stackoverflow.com/a/677212/1899640) on StackOverflow.