为什么在可执行文件或脚本名称之前需要 ./(点斜线)才能在 bash 中运行它? [英] Why do you need ./ (dot-slash) before executable or script name to run it in bash?

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

问题描述

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

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

$ ./manage.py syncdb

如果我不这样做,我会收到一条错误消息:

If I don't, I get an error message:

$ 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

(在没有 ./ 的情况下运行)

(which runs without ./)

推荐答案

因为在 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天全站免登陆