From e349e43dea0487110f865755ca25e1ee1b49992e Mon Sep 17 00:00:00 2001 From: Mingye Wang Date: Wed, 25 Dec 2019 16:37:57 +0800 Subject: [PATCH] Updated SC2230 (markdown) --- SC2230.md | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/SC2230.md b/SC2230.md index 2ce76c3..e4019c0 100644 --- a/SC2230.md +++ b/SC2230.md @@ -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 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. \ No newline at end of file