Linux中pushd命令简介
Contents
1. 概述
在本教程中,我们将了解pushd命令并介绍它在不可用的系统中的替代方法。
2. pushd命令
pushd 命令类似于cd 命令,但具有额外的功能。它允许我们在目录之间快速切换,而无需重复键入完整的目录路径:
$ pwd
/tmp
$ pushd /var # Push /var to the directory stack
/var /tmp
$ pwd
/var
$ popd
/tmp
$ pwd # Back to /tmp
/tmp
在这里,我们从*/tmp开始并推送/var目录。然后,我们使用popd返回到/tmp*而无需键入其完整路径。
3. 修复“pushd: Not Found”错误
** pushd是一个特定于 Bash 的命令,它不存在于其他 shell 中,例如ash 或dash 。因此,在这些非 Bash shell 中,我们得到“ pushd: Not Found ”错误**:
$ pushd /
sh: pushd: not found
所以,如果我们想使用pushd命令,我们必须让我们的程序使用 Bash 来执行 shell 命令。
3.1. shell脚本
在 Linux 中,shebang 指定脚本的解释器。有时,脚本会错误地假设/bin/sh始终是 Bash shell。因此,我们必须将 shebang 更改为#!/bin/bash*以使 Bash 运行脚本:*
$ cat good.sh
#!/bin/bash
pushd /
$ ./good.sh
/ /tmp
我们可以看到good.sh脚本在*/bin/sh*不是 Bash shell 的系统上运行良好。
3.2. 生成文件
与上述解决方案类似,我们可以使用SHELL变量为 Makefile 中的脚本设置解释器。我们可以在Makefile的顶部设置SHELL = /bin/bash 或在执行make时在外部设置它:
$ cat Makefile
all:
pushd /
$ make SHELL=/bin/bash
pushd /
/ /tmp
4. pushd的便携替代品
pushd命令在未安装 bash 的系统上不可用,但我们可以使用子 shell 来模仿它的行为。括号中的任何命令都在单独的 shell 中运行,并且不会影响当前 shell。
让我们模仿之前的相同示例:
$ cat subshell.sh
#!/bin/sh
echo "In $(pwd)"
(
cd /usr; echo "In $(pwd)"
(
cd /var; echo "In $(pwd)"
)
echo "Back to $(pwd)"
)
echo "Back to $(pwd)"
$ ./subshell.sh
In /tmp
In /usr
In /var
Back to /usr
Back to /tmp
如我们所见,我们遵循相同的路径从*/tmp到/var再回到/tmp*。但是,我们必须注意pushd提供了一些更多的功能,例如目录枚举 ,无法通过这种方式复制。