On UNIX-like systems over the years (most relevantly to me, Linux), I've noticed that . (current dir) is never in the $PATH by default. Why is this? I recall reading years ago that it was a security problem, but the article I read didn't explain what exactly the problem was. Is it because someone could leave a malicious version of 'ls' or 'cp' in a directory, and I'd end up running it without realizing it was there?
You answered correctly your own question, that's exactly why dot isn't in the path:
Of course, this is a very lame and useless anti-virus measure, and nothing stops you from adding dot to the path yourself.
More than a security risk, having '.' in the PATH make almost impossible to make it sure that the execution of any command acts as intended. Think about running a command like 'zip' in huge directory containing thousand of files with random names. The possibility that one of them is actually named 'zip' is not negligible and would lead to an error which is very difficult to understand (actually the file should be executable, which, however, might happen).
In particular this is true when writing scripts that keep the PATH variable of the user. A good written script should deal with all corner cases (like filenames with spaces in them or starting with '-'). But it is impractical to prevent a file in the current directory being executed instead of a system command...
Sorry, I'd like to ask this in the form of a comment to the selected answer, but I don't have any rep on superuser yet.
The security answer makes sense, but if you put "." in your PATH as the last thing, shouldn't the shell look in the current directory last as it searches for executables, and thus reduce the security risk? If it did search $PATH in order, it would find /bin/ls before it found ./ls.
So, how insecure is it for me to put "." at the end of my $PATH environment variable?
It works as I suggest. Here's how I tested:
First, add "." to the END of your PATH environment variable.
Then, put the following file in some directory, such as ~/dir1/dir2/test_which.rb:
And put this file at /usr/bin/test_which.rb
Be sure to chmod +x the files so that they're executable.
Now, if you change directory to ~/dir1/dir2, and execute test_which.rb, you'll get the output
Indeed, if you run "which test_which.rb" from anywhere, it should report
You can still execute the file in the current directory by typing:
Yes. If you put the "." in the path, you would end up sending a lot of command calls to the files in your current directory.
Even if it was last, there is still pilot error. For example, Solaris 10 lacks "top". I type "top" on my system all day long, because I think I'm on a system that has "top".