Linux pwd command

Linux 命令大全Linux Commands Reference

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:

  1. Check the environment variablePWDvalue (when using-Loption)
  2. 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

  1. Using pwd -P in scripts: to ensure that the script can obtain the correct physical path in any situation
  2. Use in combination with other commands: oftencd、lsused together with other commands.
  3. 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 directory
  • ls: lists directory contents
  • dirname: gets the directory part of a path
  • basename: gets the filename part of a path

Linux 命令大全Linux Commands Reference

Other extensions