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
PWDto 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
$PWDto be set in the following fashion: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 thepwdbuiltin).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 -Pif you want a path without symlinks.Do note that the
pwddocumentation states: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.