DavidS
DavidS

Reputation: 513

Is the environmental variable PWD always defined in Linux?

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?

Upvotes: 4

Views: 7935

Answers (2)

ensc
ensc

Reputation: 6994

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,

Upvotes: 7

ErikMD
ErikMD

Reputation: 14743

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.

Upvotes: 3

Related Questions