4

Question: Is the environment variable PWD always defined under Linux independent of the command shell (neglecting non-command shells)? In other words, will a command like "ls $PWD" always run?

DavidS
  • 483
  • 5
  • 17
  • 2
    I'm not aware of any standard environment variable called "PMD". Is it possible you mean "PWD"? –  Mar 15 '19 at 21:18
  • Yes sorry I meant PWD. I have corrected this. Thanks – DavidS Mar 15 '19 at 21:26
  • I would rather rely on the output from the `pwd` or `pwd -P` command. As in `ls $(pwd)`. – Tanktalus Mar 15 '19 at 22:05
  • @Tanktalus `pwd -P` can be useful indeed, but regarding `ls $(pwd)`, if the current directory contains spaces or other special characters, that won't work unless you do `ls "$(pwd)"` – ErikMD Mar 15 '19 at 22:08
  • @Tanktalus, `ls "$(pwd)"` is much slower to execute than `ls "$PWD"` -- the former requires a subshell (thus, a pipe pair's creation and a `fork()` in bash) just to get the output of a copy of `pwd` run in a subprocess; in the latter, the only subprocess is the copy of `ls` itself. – Charles Duffy Mar 15 '19 at 22:43
  • Duplicate of [How to define pwd as a variable in Unix shell](https://stackoverflow.com/q/20839678/608639). – jww Mar 15 '19 at 23:09

2 Answers2

7

Posix compliant shells will set this environment variable. Look for PWD in http://pubs.opengroup.org/onlinepubs/009604599/utilities/cd.html

PWD This variable shall be set as specified in the DESCRIPTION. If an application sets or unsets the value of PWD , the behavior of cd is unspecified.

or section 2.5.3 "Shell variables" in http://pubs.opengroup.org/onlinepubs/009604599/utilities/xcu_chap02.html

Variables shall be initialized from the environment... If a variable is initialized from the environment, it shall be marked for export immediately

PWD Set by the shell to be an absolute pathname of the current working directory,

ensc
  • 6,704
  • 14
  • 22
3

Is the environment variable PWD always defined under Linux independent of the command shell?

No, and I don't see why this could be the case, because the PWD variable is automatically updated (at shell initialization and) after using the cd command, which is precisely a shell builtin.

Relevant documentation about PWD can be found e.g. in:

Below is a sample Bash session to exemplify the link between PWD and cd:

/$ echo "$SHELL"
/bin/bash
/$ echo "$PWD"
/
/$ cd usr/bin/
/usr/bin$ echo "$PWD"
/usr/bin

In other words, will a command like ls $PWD always run?

Actually, the $PWD syntax corresponds to a shell parameter expansion, so ls $PWD couldn't be properly evaluated without a shell.

A remark in passing: it is strongly recommended to double-quote your shell variables, writing thereby ls "$PWD" in this case, to avoid troubles if the variable contains spaces or other special characters.

ErikMD
  • 13,377
  • 3
  • 35
  • 71