Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$PWD vs. pwd regarding portability

Tags:

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...

like image 638
helpermethod Avatar asked May 29 '12 07:05

helpermethod


People also ask

What is ${ pwd?

$PWD is an environment variable which stores the path of the current directory. This command has two flags. pwd -L: Prints the symbolic path. pwd -P: Prints the actual path.

What is the difference between pwd and pwd in Linux?

pwd is a command which prints the working directory. PWD is an environmental variable in the bash shell which allows you to determine the cwd in a script without resorting to calling the pwd command (OLDPWD is the previous working directory used by cd -).

Which is pwd command's output?

The pwd command writes to standard output the full path name of your current directory (from the root directory). All directories are separated by a / (slash). The root directory is represented by the first /, and the last directory named is your current directory.

What is $PWD in Docker?

PWD is a Docker playground which allows users to run Docker commands in a matter of seconds. It gives the experience of having a free Alpine Linux Virtual Machine in browser, where you can build and run Docker containers and even create clusters in Docker Swarm Mode.


1 Answers

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 the pwd 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. Use pwd -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.

like image 121
Mat Avatar answered Nov 25 '22 14:11

Mat