Build Your Own Which
This challenge is to build your own version of the Unix command which
. If you’re not familiar with it the which command searches through the directories listed in your $PATH environment variable.
It is used when scripting or debugging to ensure that the correct binary for a command is being executed. Especially when there are multiple versions of the same program installed.
The Challenge - Building Your Own Which
In this coding challenge you will build your own version of the Unix tool which. If you’re not familiar with it, try running the command man which on a Unix or Unix-like terminal for more details. You’ll see something like this:
WHICH(1) General Commands Manual WHICH(1)
NAME
which – locate a program file in the user's path
SYNOPSIS
which [-as] program ...
DESCRIPTION
The which utility takes a list of command names and searches the path for
each executable file that would be run had these commands actually been
invoked.
Step Zero
Let’s start at the beginning, which is step 0 - the one where you create a new project, pick a programming language and setup your development environment. As soon as you’ve done that head to step 1.
Step 1
In this step your goal is to read the command line and extract the list of commands to search for. For example if the user runs the command:
% which go ls python3
You should add go
, ls
and python3
to the list of commands to search for.
Step 2
In this step your goal is to read the PATH
environment variable and determine where to search for the requested commands.
Test what you read from the environment variable against the command:
% echo $PATH
Step 3
In this step your goal is to search the list of directories in the PATH for the binaries. Store the location of each found command.
Be sure to search the directories in the order that they appear in the PATH environment variable so you find the first one the shell will find if there is more than one.
Don’t forget to do some basic checks on each path/file considered, i.e. If it is a regular file and not a directory if the file is executable.
Step 4
In this step your goal is to output the results of the search. For example:
% which go ls python3
/usr/local/go/bin/go
/bin/ls
/usr/bin/python3
Going Further
To that this further consider either doing the build your own shell coding challenge or building one or more of the other Unix command line tools.
Help Others by Sharing Your Solutions!
If you think your solution is an example other developers can learn from please share it, put it on GitHub, GitLab or elsewhere. Then let me know - ping me a message on the Discord Server, via Twitter or LinkedIn or just post about it there and tag me. Alternately please add a link to it in the Coding Challenges Shared Solutions Github repo.
Get The Challenges By Email
If you would like to receive the coding challenges by email, you can subscribe to the weekly newsletter on SubStack here: