What is the equivalent to “which” for commands that don't refer to executables?

偶尔善良 提交于 2019-12-23 09:15:35

问题


I'm trying to find out how a specific command is defined. I've checked all locations of $PATH and could not find any file that is named like my command, so it seems to be something else.

Here is an example using nvm, that is not an executable:

me@MacBook:~$ which cat
/bin/cat
me@MacBook:~$ which nvm
me@MacBook:~$ nvm --version
0.33.8

which nvm simply returns nothing.

What is the equivalent of "which" for commands like this in unix based systems?


回答1:


The command you are looking for is type.

type nvm will show how the shell will interpret the command, so unlike which it'll show aliases, functions and unexported paths too.




回答2:


Here is an answer to a simiar question that advises against the use of which for reasons unrelated to the point in question.

That said, your assumption that which can only see executables is wrong.

It does not, however, see functions and aliases by default.

That's why the manpage of which says:

The recommended way to use this utility is by adding an alias (C shell) or shell function (Bourne shell) for which like the following:

   [ba]sh:
        which () {
          (alias; declare -f) | /usr/bin/which --tty-only --read-alias --read-functions --show-tilde --show-dot $@
        }
        export -f which

If you define this function in your .bashrc and re-source it, you should be able to do

which -a

and it should give you functions and aliases as well.

However, watch out, if maybe some profile or bashrc already defined something for which, that takes precedence (you could find that out, with type -a which btw).

If I define a script, a function and an alias, called something I get with type -a:

type -a something
something is aliased to `echo "something"'
something is a function
something () 
{ 
    echo "function something"
}    
something is /home/myself/bin/something

While which -a after creating the function gives me:

which -a something
alias something='echo "something"'
   /usr/bin/echo
   /bin/echo
something ()
{ 
    echo "function something"
}
~/bin/something


来源:https://stackoverflow.com/questions/49156104/what-is-the-equivalent-to-which-for-commands-that-dont-refer-to-executables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!