Intro To 'which' Command In Linux
2023-05-09 - By Robert Elder
I use the 'which' command to locate the full path of executables like this:
which ls
and the output from this command is the following:
/usr/bin/ls
Many common commands like 'ls', 'rm' or 'cp' are really just executable programs. I can use the 'which' command to locate where these executable programs are stored:
which ls
which rm
which cp
/usr/bin/ls
/usr/bin/rm
/usr/bin/cp
ls -latr /usr/bin/ls /usr/bin/rm /usr/bin/cp
-rwxr-xr-x 1 root root 72056 Sep 5 2019 /usr/bin/rm
-rwxr-xr-x 1 root root 142144 Sep 5 2019 /usr/bin/ls
-rwxr-xr-x 1 root root 153976 Sep 5 2019 /usr/bin/cp
Some commands like 'cd' or 'alias' are actually built into the shell itself, so the 'which' command doesn't show anything for them:
which cd
which alias
(no output)
The 'which' command is useful for debugging which version of a command actually runs:
For example, you could change the behavior of the 'ls' command by creating a simple script like this called 'ls' and changing the PATH variable. First, add this to a file called 'ls' in the current directory:
#!/bin/bash
echo "This is my custom ls command!"
then, give the 'ls' script execute permissions:
chmod u+x ls
and verify these permissions on the 'ls' file using the real 'ls' command:
ls -l
total 4
-rwxrw-r-- 1 robert robert 37 May 9 22:54 ls
and verify these permissions with the real 'ls' command:
Now before we make the final change, take note of the current value of the 'PATH' variable:
echo $PATH
/home/robert/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
And also take note of what the 'which' command shows for 'ls':
which ls
/usr/bin/ls
Now, update the 'PATH' variable to also include the current directory:
PATH="/home/robert/important:$PATH"
Verify that the 'PATH' variable was updated:
echo $PATH
/home/robert/important:/home/robert/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
Now, typing 'ls' runs the script at this location instead of the regular 'ls' executable:
ls
so the output will be this:
This is my custom ls command!
And that's why the 'which' command is my favourite Linux command.
Intro To 'stty' Command In Linux
Published 2023-10-04 |
$1.00 CAD |
Intro To 'nproc' Command In Linux
Published 2023-07-15 |
Intro To 'comm' Command In Linux
Published 2023-09-06 |
How To Force The 'true' Command To Return 'false'
Published 2023-07-09 |
A Surprisingly Common Mistake Involving Wildcards & The Find Command
Published 2020-01-21 |
A Guide to Recording 660FPS Video On A $6 Raspberry Pi Camera
Published 2019-08-01 |
Intro To 'chroot' Command In Linux
Published 2023-06-23 |
Join My Mailing List Privacy Policy |
Why Bother Subscribing?
|