Search code examples
securityshellunixtheorybsd

Why would someone set a shell variable with `which` before invoking utility?


I used to work with another, more experienced programmer who would put almost ALL of the utility calls within a shell script in the following manner:

FOO=`which foo`

$FOO -bar

After working with the guy for over a year, I knew pretty well that he was not the type to do these things on a whim, but I never really paid attention until he quit and i had to start maintaining his code. My only assumption is that, being an OpenBSD proponent and VERY security minded, it might have something to do with permissions or being able to test whether the user running the script had permissions? To counter this, however, I don't recall him ever testing against the success of setting those variables.


Solution

  • Using 'which' this way is pretty much a no-op, but it makes it much easier to maintain the code if you want to specify a utility. For example, if you find yourself running somewhere that has two installed FOO tools, and one is known be be problematic, you can hard code the correct FOO in the script and users who may have their PATH set to use the broken FOO will not be harmed (or call an insecure FOO). By assigning the value early, assigning a specific value is localized to one change rather than spreading to every instance in the script.