shellshpreloading

'which' command is incorrect


I have a shell script in my home directory called "echo". I added my home directory to my path, so that this echo would replace the other one.

To do this, I used: export PATH=/home/me:$PATH

When I do which echo, it shows the one I want. /home/me/echo

But when I actually do something like echo asdf it uses the system echo.

Am I doing something wrong?


Solution

  • which is an external command, so it doesn't have access to your current shell's built-in commands, functions, or aliases. In fact, at least on my system, /usr/bin/which is a shell script, so you can examine it and see how it works.

    If you want to know how your shell will interpret a command, use type rather than which. If you're using bash, type -a will print all possible meanings in order of precedence. Consult your shell's documentation for details.

    For most shells, built-in commands take precedence over commands in your $PATH. The whole point of having a built-in echo, for example, is that it's faster than loading /bin/echo into memory.

    If you want your own echo command to override the shell's built-in echo, you can define it as a shell function.

    On the other hand, overriding the built-in echo command doesn't strike me as a good idea in the first place. If it behaves the same as the built-in echo, there's not much point. If it doesn't, then it could break scripts that use echo expecting it to work a certain way. If possible, I suggest giving your command a different way. If it's an enhanced version of echo, you could even call it Echo.