Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to explain './' prefix before the name of an executable in terminal? [closed]

Tags:

c

terminal

unix

Every time I compile a C program, say with the cc compiler, I get an executable in the current directory. Now if I want to run it, instead of typing out just a.out or name_of_executable, I have to prefix that with this combination ./a.out.

I understand the meaning behind . (link to the current directory) and .. (link to its parent directory), also that / is a separator between directory names.

But what is the meaning of ./? Is it just a formal way to separate between referring to a name of something, and the intention to run that something (because you can't have / in your filename)?

like image 818
Morgan Wilde Avatar asked Nov 29 '22 12:11

Morgan Wilde


1 Answers

When you type the name of an executable program, the shell searches for it in a sequence of directories whose names are stored in the $PATH environment variable.

The current directory, ., normally isn't (and shouldn't be) in your $PATH. So if you type just a.out, the shell won't find it -- unless there happens to be a /usr/bin/a.out, or /usr/local/bin/a.out, or ....

Why shouldn't . be in your $PATH? (Sometimes, on some systems, it is.) Because it creates a security hole. If . is at the front of your $PATH, then if you cd to a directory that happens to contain a command called ls, it's very easy to execute it accidentally, with arbitrarily bad consequences. Even if . is at the end of $PATH, you can still run into problems if the little program you just compiled, or the script you just wrote, happens to have the same name as a standard command. I've seen a lot of people becoming very confused because the named a test program test, but typing test runs /bin/test.

A command can be either a built-in command (provided by the shell) or the name of an executable file. If you type ls, the shell finds an executable file called ls in one of the directories named in your $PATH. If you type a.out, there is no executable file of that name in any of the directories named in $PATH -- thus the error message.

Typing a path to the executable file (even a relative path like ./a.out) causes the shell to bypass the $PATH search; you're telling the shell exactly where to find the executable file rather than asking the shell to search for it.

like image 101
Keith Thompson Avatar answered Dec 05 '22 03:12

Keith Thompson