Linux pwd command
The Linux pwd (full English spelling: print work directory) command is used to display the full path of the working directory where the current user is located.
Executing the pwd command immediately tells you the absolute path name of the working directory you are currently in.
Syntax
pwd [--help][--version]
Parameter description:
| Option | Description |
|---|---|
-L |
Display the logical path (default behavior), resolve symbolic links |
-P |
Display the physical path, do not resolve symbolic links |
--help |
Display help information |
--version |
Display version information |
How the pwd command works
pwdThe command determines the current working directory in the following ways:
- Check the environment variable
PWDvalue (when using-Loption) - or physically determine the path by traversing parent directories (when using
-Poption)
Practical applications of the pwd command
Basic usage examples
The simplest usage is to enter the command directly:
$ pwd /home/username/projects
Using the -P option
When you are in a symbolic link directory:
$ ln -s /var/www/html myweb $ cd myweb $ pwd /home/username/myweb # 逻辑路径 $ pwd -P /var/www/html # 物理路径
Using it in scripts
pwdOften used in scripts to get the current directory:
#!/bin/bash CURRENT_DIR=$(pwd) echo "当前目录是: $CURRENT_DIR"
Frequently Asked Questions
1. What is the difference between pwd and echo $PWD?
pwdis a built-in command, while$PWDis an environment variable. In most cases, they output the same, butpwdcommand can take options (such as-P), while$PWDalways displays the logical path.
2. Why is the -P option needed?
When working in a symbolic link directory, sometimes you need to know the actual physical location rather than the symbolic link path, and at this time-Pthe option is very useful.
3. Can the pwd command fail?
Under normal circumstancespwdit will not fail, but if the current directory is deleted (in another terminal session),pwdit may display an error.
Best practice recommendations
- Using pwd -P in scripts: to ensure that the script can obtain the correct physical path in any situation
- Use in combination with other commands: often
cd、lsused together with other commands. - Note on symbolic links: when there are symbolic links in the path, clearly know whether you need the logical path or the physical path
Extended knowledge
History of the pwd command
pwdThe command first appeared in early versions of Unix and was part of the Bourne shell. Now it is part of the POSIX standard, and all POSIX-compatible systems include this command.
Related commands
cd: changes the working directoryls: lists directory contentsdirname: gets the directory part of a pathbasename: gets the filename part of a path
Linux Commands Reference