Linux FAQ: Why Do We Need a Dot Slash Before a Local Command



  • One of the earlier things that you learn when working with Linux, or any UNIX system for that matter, is that if you want to run a command in your current working directory, that you need to preface the command with a dot slash or ./ or else the command will not run. But why is this? We have two questions to answer: first why does this happen mechanically and second why was this behaviour desired?

    First, the mechanics. Commands are not special cases in UNIX, including Linux, and the shell needs to know what file you want to execute in order to run it. When we are dealing with files we are used to the concept of the absolute path and the relative path. We use this all of the time. We expect that if something is in our current working directory that we can access it without needing to supply the full path.

    Executables do not work this way, the current working directory will not allow us to execute a file within it by default. You can only execute files that exist within your $PATH or by specifying an absolute path or by being extra explicit about a relative path by adding the ./ to the beginning of a command existing in your current working directory.

    So we can run commands in these ways...

    1. By uses the absolutely path:

      /usr/bin/command

    2. By adding the path of the command to our $PATH variable in our shell environment. So assuming /usr/bin is in our $PATH from the example above:

      command

    3. Or by being in the working directory of the command and using the ./ notation.

      cd /usr/bin
      ./command

    Second, why do we do this? It seems obvious that we would want to run a command if it exists in the directory in which we are located. But in reality, this is a security problem. If the shell automatically executed things that were local to us we would have an easy way to produce a sneak attack on someone - just drop files with the same name as something that they are likely to want to use, or something that they might easily mistype, and if they happen to be in a directory where that file exists, it will be executed with their privileges. A very powerful attack vector.

    In general, executable binaries are kept in central, protected locations like /bin, /sbin, /usr/bin, /usr/sbin and so forth. Not sprinkled throughout the filesystem. This is for security purposes, as well as ease of use. When a binary exists somewhere else we want there to be some acknowledgement of this before the file is executed and we do this with the ./ notation to make it clear to the shell that we know what we are doing.

    It's all about security.

    It is important to note that this behaviour is part of your shell, but all shells do this by default. But the current working directory can be made part of the executable path if so desired. So while this behaviour is effectively ubiquitous, it is by convention.