为什么在脚本名称之前需要./(点 - 斜杠)在bash中运行它? [英] Why do you need ./ (dot-slash) before script name to run it in bash?

查看:150
本文介绍了为什么在脚本名称之前需要./(点 - 斜杠)在bash中运行它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在bash中运行脚本时,我必须在开头写 ./

When running scripts in bash, I have to write ./ in the beginning:

$ ./manage.py syncdb

如果我不,错误消息:

$ manage.py syncdb
-bash: manage.py: command not found

这是什么原因?我认为。是当前文件夹的别名,因此这两个调用应该是等效的。

What is the reason for this? I thought . is an alias for current folder, and therefore these two calls should be equivalent.

不知道为什么我在运行应用程序时不需要 ./ ,例如:

I also don't understand why I don't need ./ when running applications, such as:

user:/home/user$ cd /usr/bin
user:/usr/bin$ git

(不包含 ./

推荐答案

因为在Unix上,通常当前目录不在 $ PATH

Because on Unix, usually, the current directory is not in $PATH.

命令,shell查找由 PATH 变量指定的目录列表。

When you type a command the shell looks up a list of directories, as specified by the PATH variable. The current directory is not in that list.

当前目录不在该列表中。

The reason for not having the current directory on that list is security.

假设你是root,进入另一个用户目录,输入 sl ,而不是 ls 。如果当前目录在 PATH 中,shell将尝试在该目录中执行 sl 程序(因为没有其他 sl 程序)。 sl 程序可能是恶意程序。

Let's say you're root and go into another user's directory and type sl instead of ls. If the current directory is in PATH, the shell will try to execute the sl program in that directory (since there is no other sl program). That sl program might be malicious.

它适用于 ./ ,因为 POSIX指定命令名称包含 / 将直接用作文件名,从而禁止在 $ PATH 中搜索。您可以使用完整路径获得完全相同的效果,但 ./ 更短,更容易书写。

It works with ./ because POSIX specifies that a command name that contain a / will be used as a filename directly, suppressing a search in $PATH. You could have used full path for the exact same effect, but ./ is shorter and easier to write.

编辑

sl 部分只是一个例子。顺序搜索 PATH 中的目录,并且在执行程序匹配时。因此,根据 PATH 的外观,输入正常命令可能会或不足以在当前目录中运行程序。

That sl part was just an example. The directories in PATH are searched sequentially and when a match is made that program is executed. So, depending on how PATH looks, typing a normal command may or may not be enough to run the program in the current directory.

这篇关于为什么在脚本名称之前需要./(点 - 斜杠)在bash中运行它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆