BASH命令查找与路径规则的一点细节

陪她去流浪 桃子 2019年02月15日 阅读次数:1684

发现

今天在查nohup的 manual 时,环境变量一节提到了对 PATH 的使用。

ENVIRONMENT

     PATH  Used to locate the requested utility if the name contains no `/' characters.

就是说,当 命令 中不包含 / 字符的时候,PATH 才会被用于定位命令。 这句话暗示了另外一个事情:如果命令中包含了/字符,那么它不会在PATH中搜索。 所以它要么是绝对路径,要么是相对路径。

之所以写这篇文章,是因为:到目前为止,我在执行当前目录下子目录中的命令的时候,也总是加上./。作为参数的时候也经常这样。 看了nohup的这个说明之后,发现,好像不用这样了。

测试

比如,假设有这样一个目录树:

taoblog (master)$ tree server/
server/
├── main.go
└── server     <- 我要执行这个命令

0 directories, 2 files

如果我要执行server命令,平常我都是输入的./server/server。但我觉得直接输入server/server应该就可以了。 因为命令server/server命令中包含了/,所以不会从PATH中查找。再由于不是以/开头,所以不是绝对路径。那么,就只能是相对路径了,相对于当前目录。

经测试,以上结论正确

弊端

但是,这样有一个弊端。 当输入部分命令并尝试按TAB补全命令的时候,终端可能不会自动补全子目录,可能是因为它觉得我们输入的是PATH中的命令。

考证

Go 语言官方博客刚刚发表了一篇博客,说是在 Windows 系统关于命令路径查找的一个安全问题,里面正好提到了 Unix 中关于命令查找的说明, 我直接贴过来,注意我加粗的那句话:

On Unix, this idea first appeared in Seventh Edition Unix's Bourne shell (1979). The manual explained:

The shell parameter $PATH defines the search path for the directory containing the command. Each alternative directory name is separated by a colon (:). The default path is :/bin:/usr/bin. If the command name contains a / then the search path is not used. Otherwise, each directory in the path is searched for an executable file.

这篇文章的内容已被作者标记为“过时”/“需要更新”/“不具参考意义”。