一、pwd命令
2、在终端中输入pwd命令并按下回车,即可显示当前工作目录路径。
pwd
/home/user/Documents
3、pwd命令在脚本中也可用于获取当前工作目录,供后续的操作使用。
二、echo命令
1、echo $PWD命令也可以显示当前工作目录路径。
2、在终端中输入echo $PWD命令并按下回车,即可显示当前工作目录路径。
echo $PWD
/home/user/Documents
3、$PWD是系统环境变量之一,表示当前工作目录的路径。
三、ls命令
1、ls -d $PWD命令可以显示当前工作目录的路径。
2、在终端中输入ls -d $PWD命令并按下回车,即可显示当前工作目录路径。
ls -d $PWD
/home/user/Documents
3、ls -d表示仅列出当前目录的详细信息,$PWD表示当前工作目录的路径。
四、bash内置变量
1、$PWD也是bash内置变量之一,可以直接在脚本中使用。
echo $PWD
/home/user/Documents
2、除了$PWD外,bash还有一些其他的内置变量,如$USER、$HOME等,可以在终端或脚本中使用,具体可以通过help命令查看。
help
...
pwd: pwd [-LP]
Print the current working directory.
Options:
-L force PWD to be absolute symbolic links.
-P use the physical directory structure without following symbolic
links.
-P and -L can be combined.
Exit Status:
Returns 0 unless an invalid option is given or the current directory cannot
be read.
TYPE: Alias
五、其他命令
1、readlink -f $(which bash)命令可以显示bash所在目录的绝对路径。
readlink -f $(which bash)
/bin/bash
2、which命令可以显示某个命令所在的位置。
which bash
/bin/bash
3、realpath命令可以显示某个路径的绝对路径。
realpath .
/home/user/Documents
六、小结
Linux中显示当前工作目录路径的方式有多种,常见的有pwd、echo $PWD、ls -d $PWD和bash内置变量$PWD。此外,还可以使用readlink和realpath等命令来显示路径。在实际的开发中,可以根据实际需求来选择合适的方法。
