Hacker News new | ask | show | jobs
by teddyh 1213 days ago
I was taught, back in the late 20th century, to never use the “which” program in shell scripts, since that program has its own logic on what programs are available, and that might differ from the method the actual shell uses to find programs, and this could obviously lead to subtle bugs. I was taught to use “type” instead, since, IIRC, “command” did not exist at the time.
1 comments

> I was taught, back in the late 20th century, to never use the “which” program in shell scripts, since that program has its own logic on what programs are available, and that might differ from the method the actual shell uses to find programs, and this could obviously lead to subtle bugs.

This reminds me of the suggestion not to use access(2) and X_OK to decide to call execve(2) -- because the kernel behavior of executing the binary may work differently and fail for some other reason, or perhaps even there's a race condition where the executable bit gets removed between your calls.

This is typical advice given to people writing shells.

On this basis I would say using either which or command -v in unsound; neither of them are a guarantee that execve(2) will succeed. But like many things done in shell scripts, it's a "good enough" kind of solution that will do the right thing a majority of the time.