2

I was wondering what happens in the following situation. Suppose I have an executable file in a directory that is in PATH in .bashrc. If I copy the file into another directory that is set in PATH also, and I execute from terminal that file, which copy am I running?

Can I set a preference to say “if a file exists in more than one place within PATH, execute that in the first place instead of that in the second place.”

6
  • The directory`s are tried in order, from left to right. Jul 27, 2014 at 19:53
  • What do you mean¿ I do not follow what you are saying. Jul 27, 2014 at 19:55
  • I have one question about your question. Would you question be the same if you do not try to execute the file before copying it to another place. Jul 27, 2014 at 20:00
  • I am not on a computer with Linux installed right now. I am free to ask, right¿ Jul 27, 2014 at 20:03
  • join me for a chat, so I can discover more clearly what the question is. — chat.stackexchange.com/rooms/15994/… Jul 27, 2014 at 20:10

1 Answer 1

4

The Quick Answer

To find out which copy bash will try to execute, use the bash's builtin utility type. To find out which copy of du, for instance, will be executed, run:

$ type du
du is /usr/bin/du

The Theory

When you ask bash to execute something, bash performs two steps:

First, it checks its cache for the file's location. This is a list of executable names and where the file was located the last time that bash executed it.

Second, if the file is not in the cache, it checks the path, searching each directory in the path from left to right.

Note that the answer, then, depends on whether you happened to have run the executable in the current shell before doing the copy. If so, bash may have saved its location in the cache and it will ignore any new locations that it may be in after you make copies. If it is not in the cache, then which file is executed depends only on the order of the directories in the path.

More Details

To see what is in bash's current cache, run:

$ declare -p BASH_CMDS
declare -A BASH_CMDS='([du]="/usr/bin/du" )'

The above shows that only du was in the cache when I ran that. If I executed more commands and then ran it again, there would be more in the cache.

To see what the current path is, run:

$ echo $PATH
/bin:/usr/bin:/opt/bin:/usr/local/bin:/usr/X11R6/bin

The path is a colon-separated list. The above shows five directories in the path. They will be searched starting from the left and working to the right.

Can I set a preference?

Yes, you can change the order of directories in the path.

Alternatively, for interactive work, you can set an alias. For example:

$ alias dd=/opt/bin/dd

After the above alias is set, you can type dd at the command line and bash will ignore the cache and ignore the PATH, and run (or try to run) /opt/bin/dd.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .