Linux pwd command
The Linux pwd (short for print work directory) command is used to display the full path of the current user's working directory.
Running the pwd command immediately tells you the absolute path name of your current working directory.
Syntax
pwd [--help][--version]
Parameter description:
| Option | Description |
|---|---|
-L |
Display the logical path (default behavior), resolving symbolic links |
-P |
Display the physical path, without resolving symbolic links |
--help |
Display help information |
--version |
Display version information |
How the pwd command works
pwd The command determines the current working directory in the following ways:
- Check the environment variable
PWDvalue (when using the-Loption) - or determine the path physically by traversing parent directories (when using the
-Poption)
Practical applications of the pwd command
Basic Usage Example
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 # 物理路径
Use in Scripts
pwd Often 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?
pwd is a built-in command, while $PWD is an environment variable. In most cases they output the same, but the pwd command can take options (such as -P), while $PWD always 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; in that case the -P option is very useful.
3. Can the pwd command fail?
Under normal circumstances pwd will not fail, but if the current directory is deleted (in another terminal session),pwd may display an error.
Best Practice Recommendations
- Using pwd -P in scripts: to ensure the script can obtain the correct physical path in any situation
- Use in combination with other commands: often used with
cd,lsand other commands - Be careful with symbolic links: when a path contains symbolic links, know clearly whether you need the logical or physical path
Additional knowledge
History of the pwd command
pwd The command first appeared in early versions of Unix as part of the Bourne shell. Now it is part of the POSIX standard, and all POSIX-compliant systems include this command.
Related commands
cd: change the working directoryls: list directory contentsdirname: get the directory part of a pathbasename: get the file name part of a path
Linux Command Reference