What corner cases must we consider when parsing $PATH on Linux?

安稳与你 提交于 2019-12-05 04:52:06

One thing that once surprised me is that the empty string in PATH means the current directory. Two adjacent colons or a colon at the end or beginning of PATH means the current directory is included. This is documented in man bash for instance.

It also is in the POSIX specification.

So

PATH=:/bin
PATH=/bin:
PATH=/bin::/usr/bin

All mean the current directory is in PATH

I'm not sure this is a problem with Linux in general, but make sure that your code works if PATH has some funky (like, UTF-8) encoding to deal with directories with fancy letters. I suspect this might depend on the filesystem encoding.

I remember working on a bug report of some russian guy who had fancy letters in his user name (and hence, his home directory name which appeared in PATH).

This is minor but I'll added it since it hasn't already been mentioned. $PATH can include both absolute and relative paths. If your crawling the paths list by chdir(2)ing into each directory, you need to keep track of the original working directory (getcwd(3)) and chdir(2) back to it at each iteration of the crawl.

The existing answers cover most of it, but it's worth covering parts of the question that wasn't answered yet:

  1. $ and ~ are not special in the value of $PATH.
  2. If $PATH is not set at all, execvp() will use a default value.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!