$ PWD与有关PWD可移植性 [英] $PWD vs. pwd regarding portability
问题描述
我在写一个shell脚本,分析当前工作目录的路径(打印像所有基本名的当前目录以上)。
到目前为止,我一直在使用环境变量 PWD
来解析路径,但我不知道是否
- 我可以在
PWD
来始终设置 计数 - 要给予同样的结果每个平台上
难道可能是更好的使用 PWD
壳内置?我需要这个脚本运行在尽可能多的平台,尽可能,所以我只是想知道...
POSIX 要求 $ PWD
在以下方式进行设置:
PWD
此变量应当重新present当前工作目录的绝对路径。它不应包含在点或点 - 点的任何组件。该值是由CD实用程序初始化期间设置,并通过用sh效用
块引用>所以,你可以依赖于被设置&ndash的;但千万注意......绝对路径...,没有的的的绝对路径。
庆典
(至少最近的版本)会记得什么符号链接,你跟着当设置$ PWD
(和PWD
内置)。pwd命令
(即外部命令)不会。所以,你会得到不同的结果出现,这可能会,也可能不会,对你很重要。使用PWD -P
如果你想在不符号链接的路径。请注意,
PWD
文档状态:
如果应用程序设置或取消设置PWD的值,PWD的行为是不确定的。
块引用>所以,千万不要做:)
总之,这里没有赢家。环境变量将在那里在POSIX的壳,作为将外部指令和可能一个内置的太。选择最适合您的需要,是你是否关心符号链接与否最重要的事情之一。
I'm writing a shell script which parses the path of the current working directory (printing a like of all basenames above the current directory).
So far, I've been using the environment variable
PWD
to parse the path but I wonder if
- I can count on
PWD
to be always set- to give the same result on every platform
Would it possibly be better to use the
pwd
shell-builtin? I need this script to run on as many platforms as possible, so I just wondered...解决方案POSIX requires
$PWD
to be set in the following fashion:PWD
This variable shall represent an absolute pathname of the current working directory. It shall not contain any components that are dot or dot-dot. The value is set by the cd utility, and by the sh utility during initialization.
So you can rely on that being set – but do note "... an absolute path...", not the absolute path.
bash
(at least recent versions) will remember what symlinks you followed when setting$PWD
(and thepwd
builtin).command pwd
(that is, the external command) will not. So you'll get different results there, which might, or might not, be important for you. Usepwd -P
if you want a path without symlinks.Do note that the
pwd
documentation states:If an application sets or unsets the value of PWD, the behavior of pwd is unspecified.
So, don't do that :)
In short, there is no winner here. The environment variable will be there in POSIX shells, as will the external command and possibly a built-in too. Choose the one that best fits your need, the important thing being whether you care about symlinks or not.
这篇关于$ PWD与有关PWD可移植性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!