Skip to contentSkip to conversation

Makefile, copy-firmware: Use portable "command -v" to detect installed programs

PATCH In review Eli Schwartz 1 participant 2 messages Nov 26, 2023 Kbuild

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 Makefile, copy-firmware: Use portable "command -v" to detect installed programs

The "which" utility is not guaranteed to be installed either, and if it is, its behavior is not portable either. This means that when rdfind / pre-commit are installed, the which check will report a fatal error because the which tool did not exist and the shell returned a nonzero status when attempting to fork+exec. If it did exist, it might not be an implementation of which that returns nonzero when commands do not exist.

Conversely, the "command -v" shell builtin is required to exist in all POSIX 2008 compliant shells, and is thus guaranteed to work everywhere.

For some in-depth discussions on the topic, see:
- https://mywiki.wooledge.org/BashFAQ/081
- https://unix.stackexchange.com/questions/85249/why-not-use-which-what-to-use-then/85250#85250

Examples of open-source shells likely to be installed as /bin/sh on Linux, which implement the 15-year-old standard: ash, bash, busybox, dash, ksh, mksh and zsh.

A side benefit of using the POSIX portable option is that it requires neither an external disk executable, nor (because unlike "which", the exit code is reliable) a subshell fork. This therefore represents a mild speedup.

---
 Makefile         | 2 +-
 copy-firmware.sh | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)
Makefile +1 -1
index 1d28d8a..f7e6323 100644
@@ -6,7 +6,7 @@ FIRMWAREDIR = /lib/firmware
 all:
 
 check:
-	@if ! which pre-commit >/dev/null; then \
+	@if ! command -v pre-commit >/dev/null; then \
 		echo "Install pre-commit to check files"; \
 		exit 1; \
 	fi
copy-firmware.sh +1 -1
index f9b1f0f..6f2268b 100755
@@ -69,7 +69,7 @@ if [ -z "$destdir" ]; then
 	exit 1
 fi
 
-if ! which rdfind 2>/dev/null >/dev/null; then
+if ! command -v rdfind >/dev/null; then
 	echo "ERROR: rdfind is not installed"
 	exit 1
 fi
Signature · 1 line
2.41.0
#1 lore raw

Oops, did not realize the first copy already sent.