Linux – Difference between a.out and ./a.out

linuxterminal

My Confusion

a.out is the output of the programs which I execute in my Ubuntu 12.10.
In Red Hat system when I execute a.out in the terminal it executes. While in Ubuntu I have to execute ./a.out to get the output. 'a.out' doesn't work.

Can somebody explain what is the difference between the commands?

Best Answer

The behaviour you experience depends most likely on differences in the environment variable $PATH. The $PATH is essentially a colon-separated list of directories, which are searched in order for a particular executable when a program is invoked using anexec operating system call. The $PATH can contain relative path components, typically . or an empty string, which both refer to the current working directory. If the current directory is part of $PATH, files in the current working directory can be executed by just their name, e.g. a.out. If the current directory is not in $PATH, one must specify a relative or absolute path to the executable, e.g. ./a.out.

Having relative path components in $PATH has potential security implications as executables in directories earlier in $PATH overshadow executables in directories later in the list. Consider for example an attack on a system where the current working directory path . preceeds /bin in $PATH. If an attacker manages to place a malicious script sharing a name with a commonly used system utility, for instance ls, in the current directory (which typically is far easier that replacing binaries in root-owned /bin), the user will inadvertently invoke the malicious script when the intention is to invoke the system ls. Even if . is only appended at the end of $PATH, a user could be tricked to inadvertently invoke an executable in the current directory which shares a name with a common utility not found on that particular system. This is why it is common not to have relative path components as part of the default $PATH.