by Oliver; 2014
16. which
which shows you the path of a command in your
PATH.
For example, on my computer:
$ which less
/usr/bin/less
$ which cat
/bin/cat
$ which rm
/bin/rm
If there is more than one of the same command in your
PATH,
which will show you the one
which you're using (i.e., the first one in your
PATH).
Suppose your
PATH is the following:
$ echo $PATH
/home/username/mydir:/usr/local/bin:/bin:/usr/bin:/usr/local/sbin
And suppose
myscript.py exists in 2 locations in your
PATH:
$ ls /home/username/mydir/myscript.py
/home/username/mydir/myscript.py
$ ls /usr/local/bin/myscript.py
/usr/local/bin/myscript.py
Then:
$ which myscript.py
/home/username/mydir/myscript.py # this copy of the script has precedence
You can use
which in if-statements to test for dependencies:
if ! which mycommand > /dev/null; then echo "command not found"; fi
My friend, Albert, wrote a nice tool called
catwhich, which
cats the file returned by
which:
#!/bin/bash
# cat a file in your path
file=$(which $1 2>/dev/null)
if [[ -f $file ]]; then
cat $file
else
echo "file \"$1\" does not exist!"
fi
This is useful for reading files in your
PATH without having to track down exactly what directory you put them in.
<PREV
NEXT>