现在的位置: 首页 > 综合 > 正文

why do you need ./ to execute programs in current directory?

2013年09月29日 ⁄ 综合 ⁄ 共 2289字 ⁄ 字号 评论关闭

Shell 通过保存在PATH环境变量中的文件路径列表来寻找命令和程序。

环境变量将信息存储在其他命令和程序可以访问到的地方,环境变量存储诸如,你正在使用的shell,你的登录名,你当前的工作路径等信息。

为了查看当前定义的所有环境变量的列表,在命令提示符的地方输入set。

 

当你在shell命令提示符的地方输入命令的时候,shell会按顺序在PATH变量里列出的每一个路径里寻找该命令的程序文件。

发现的第一个匹配你所输入命令的程序会得到运行。如果命令的程序文件并不在PATH环境变量列出的路径里,shell会返回一个“command not found”的错误。

 

默认情况下,shell不会在你的当前工作目录或者home目录寻找命令。这实在是一个安全机制,以便你不会以外的执行程序。

如果一个怀有恶意的(malicious)用户将一个名为ls的有害程序放在你的home目录下会怎么样?

如果你输入ls,shell会于在/bin目录里找到真正的程序之前,在你的home路径里找到假冒伪劣的程序,

你认为会发生什么?如果你想到了什么不好的东西,那你上对路了。

 

因为PATH没有将当前路径(.)作为它搜索的地方之一,你当前路径下的程序必须以绝对路径或者以定义为./programname的相对路径进行调用。

 

为了查看PATH的内容,可以输入这个命令: 

[alberto@digital alberto]$ echo $PATH

 /bin:/usr/bin:/opt/bin:/usr/local/bin:/usr/X11R6/bin:/opt/kde/bin:

注意:目录的路径是以:分隔开的。

 

over.

This is the reason why you need ./ to execute programs in current directory.

 

original writing is as following,from “complete idiots guide to linux”

 

Techno Talk: The PATH Environment Variable

The shell looks for commands and programs in a list of file paths stored in the PATH environment variable.
An environment variable stores information in a place where other programs and commands can access it.
Environment variables store information such as the shell you are using, your login name, and your current

working directory. To see a list of all the environment variables currently defined, type set at the prompt.

When you type a command at the shell prompt, the shell will look for that command’s program file in each
directory listed in the PATH variable, in order. The first program found matching the command you typed
will be run. If the command’s program file is not in a directory listed in your PATH environment variable,
the shell returns a “command not found” error.

By default, the shell does not look in your current working directory or your home directory for
commands. This is really a security mechanism so that you don’t execute programs by accident. What if a
malicious user put a harmful program called ls in your home directory? If you typed ls and the shell
looked for the fake program in your home directory before the real program in the /bin directory, what do
you think would happen? If you thought bad things, you are on the right track.

Since your PATH doesn’t have the current directory (.) as one of its search places, programs in your current
directory must be called with an absolute path or a relative path specified as ./programname.

 

To see what directories are part of your PATH, enter this command:
  echo $PATH
  [alberto@digital alberto]$ echo $PATH
  /bin:/usr/bin:/opt/bin:/usr/local/bin:/usr/X11R6/bin:/opt/kde/bin:
Note that directory paths are separated by a colon (:).

抱歉!评论已关闭.